Deep Learning美食评分 Giesen 2021-12-31 代码实现如下1234#解压图像文件,用Linux命令!unzip data_foodscore.zip -d data/datafood 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182import paddlefrom paddle.io import Datasetimport pandas as pdimport numpy as npfrom PIL import Image#自定义数据集class FoodDataset(Dataset): #初始化数据集 def __init__(self,train=True,transforms=None): #调用基类构造函数 super().__init__() #传入数据预处理 self.transforms=transforms #导入csv df_foodscore=pd.read_csv("data/datafood/FoodScore.csv") #dataframe类型数据 offset=int(len(df_foodscore)*0.7) if train==True: df_foodscore=df_foodscore[:offset] else: df_foodscore=df_foodscore[offset:] self.score=np.array(df_foodscore["score"]).astype("float32") #把dataframe转化numpy.array 标签数据集 picname=df_foodscore["ID"] self.data=[] #图像数据集 for name in picname: filepath="data/datafood/data_foodscore/{}.jpg".format(name) photo=Image.open(filepath) matrix=np.array(photo).astype("float32") self.data.append(matrix) #获取单个数据 def __getitem__(self,index): data=self.data[index] if self.transforms!=None: data=self.transforms(data) #把数据预处理应用到每个图像 label=self.score[index] return data,label #回去数据集长度 def __len__(self): return len(self.score) 1234567891011121314151617181920#数据预处理,图像统一尺寸、归一化、张量import paddle.vision.transforms as T#数据预处理组合trans=T.Compose([T.Resize([128,128]),T.Normalize(mean=[0,0,0],std=[255,255,255],data_format="HWC"),T.ToTensor()])#创建数据集对象train_dataset=FoodDataset(train=True,transforms=trans)eval_dataset=FoodDataset(train=False,transforms=trans)#数据加载,分批train_loader=paddle.io.DataLoader(dataset=train_dataset,batch_size=20,shuffle=True)eval_loader=paddle.io.DataLoader(dataset=eval_dataset,batch_size=20,shuffle=True) 12345678910111213141516171819202122232425262728293031323334#组建网络class FoodNet(paddle.nn.Layer): #初始化每层结构对象 def __init__(self): super().__init__() self.flatten=paddle.nn.Flatten() self.linear=paddle.nn.Linear(128*128*3,1) #前向传播 def forward(self,x): y=self.flatten(x) y=self.linear(y) return y #实例化网络foodNet=FoodNet()paddle.summary(foodNet,(10,3,128,128)) 12345678910111213141516171819202122#使用高层API#封装模型对象model=paddle.Model(foodNet) #配置训练model.prepare(optimizer=paddle.optimizer.Adam(parameters=model.parameters(),learning_rate=0.001), loss=paddle.nn.MSELoss())#训练模型model.fit(train_data=train_loader,batch_size=20,verbose=1,epochs=10)#保存模型model.save("mymodel/FoodNet") 1234567891011121314151617181920212223242526272829303132333435363738import matplotlib.pyplot as plt#创建模型对象foodNet=FoodNet()model=paddle.Model(foodNet) #调用高层API对模型对象封装#加载模型参数model.load("mymodel/FoodNet")#加载图片photo=Image.open("myfood/1.jpg")#把图像显示出来plt.imshow(photo)#把图片数字化im=np.array(photo).astype("float32")#把新的图像数据进行预处理im=trans(im)im=im.reshape([1,3,128,128]) #进行预测result=model.predict_batch(im)print("分数:{}".format(result[0])) 尾巴 飞桨AI Studio - 人工智能学习实训社区 GitHub - GiesenC/DeepLearning: DeepLearning model training, evaluation and prediction related code.