一、数据介绍:
图像来源:Flickr上收集用户上传的经人工筛选后的196张食物图像
因变量:由5人小组对每张美食图像进行1~5评分,最后取平均分作为每张图像的最终得分
(其中1分代表图像非常不吸引人,5分代表图像非常吸引人)
二、建模步骤:
2.1准备𝑋+𝑌数据
import pandas as pd
MasterFile=pd.read_csv('./FoodScore.csv') #读取美食图像评分的数据
print(MasterFile.shape)
MasterFile[0:5]
2.2数据展示
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))
2.3切分训练集与测试集
from sklearn.model_selection import train_test_split
X0,X1,Y0,Y1=train_test_split(X,Y,test_size=0.5,random_state=0)
2.4线性回归模型构建
from keras.layers import Dense, Flatten, Input
from keras import Model
input_layer=Input([IMSIZE,IMSIZE,3])
x=input_layer
x=Flatten()(x) #第2个输入的是128*128*3的立体矩阵
x=Dense(1)(x) #Dense()函数实现的是将向量x进行线性组合变成标量x,然后输出
output_layer=x
model=Model(input_layer,output_layer)
model.summary()
2.5模型编译
from keras.optimizers import Adam
model.compile(loss='mse',optimizer=Adam(lr=0.001),metrics=['mse'])
2.6模型拟合
model.fit(X0,Y0,
validation_data=[X1,Y1],
batch_size=100,
epochs=100)
2.7模型预测
MyPic=Image.open('mypic.jpg')
MyPic
MyPic=MyPic.resize((IMSIZE,IMSIZE))
MyPic=np.array(MyPic)/255
MyPic=MyPic.reshape((1,IMSIZE,IMSIZE,3))
model.predict(MyPic)
预测结果:array([[3.170478]], dtype=float32)