三、Tensorflow图像处理预算

@

前文

Tensorflow图像处理预算

#%%

# 一、线性回归模型的tensorflow实现
# 二、掌握teonsorflow的框架下建立X到Y的线性回归模型
#    掌握模型构建的流程
#    掌握关于数据的处理方法

# 三、实验内容
# P50 3.2.2

导入数据

#%%

import pandas as pd

MasterFile = pd.read_csv("D:FoodScore.csv")
MasterFile[:5]

直方图


MasterFile.hist()

分离因变量

#%%
import numpy as np

fileName = MasterFile["ID"]
#fileName
N = len(fileName)
Y = np.array(MasterFile["score"]).reshape([N, 1])

处理图像数据

#%%
from PIL import Image

Imsize = 128
X = np.zeros([N, Imsize, Imsize, 3])
for i in range(N):
    myfile = fileName[i]
    Im = Image.open("D:data_foodscore\\"
                    + myfile + ".jpg")
    Im = Im.resize([Imsize, Imsize])
    Im = np.array(Im) / 255
    X[i,] = Im

展示图片

#%%
from matplotlib import pyplot as plt

plt.figure()
fig, ax = plt.subplots(2, 5)
fig.set_figheight(7.5)
fig.set_figwidth(15)
ax = ax.flatten()
for i in range(10):
    ax[i].imshow(X[i,])
    ax[i].set_title(np.round(Y[i], 2))

划分训练集和测试集

#%%
from sklearn.model_selection import train_test_split
# X0, X1, Y0, Y1 = test_split(X, Y, test_size=0.5, random_state=0)
X0, X1, Y0, Y1 = train_test_split(X, Y, test_size=0.5, random_state=0)

构建模型

#%%
from keras.layers import Dense, Flatten, Input
from keras import Model

input_Layer = Input([Imsize, Imsize, 3])
layer2 = Flatten()(input_Layer)
layer3 = Dense(1)(layer2)
output_layer = layer3

model = Model(input_Layer, output_layer)
model.summary()

模型编译

#%%
from keras.optimizers import Adam

model.compile(loss="mse", optimizer=Adam(lr=0.001), metrics=["mse"])

#model.compile(loss="mse",optimizer="adam",metrics=["mse"])

# from keras.optimizers import Adam
# #?Adam

模型拟合

#%%
model.fit(X0, Y0, validation_data=[X1, Y1], batch_size=100, epochs=100)

模型预测

#%%

mypic = Image.open("E:\ChromeDownload\wlop\\532754530.jpg")
mypic = mypic.resize([128, 128])
mypic = np.array(mypic) / 255
mypic = mypic.reshape([1, 128, 128, 3])

y_pre = model.predict(mypic)
y_pre

GitHub下载地址

TensorflowOne

posted @ 2021-11-13 22:14  李好秀  阅读(127)  评论(0编辑  收藏  举报