CNN人脸表情识别简单尝试
目录
一:查看fer2013数据集(cvs格式)
二:使用Pandas读取csv
三:使用cv2查看其中一张图片
四:将数据集划分
五:将数据转换为数组(array)格式,否则keras会报错
六:使用matplotlib显示照片
七:搭建模型
八:查看模型结构图(使用pydot)
九:开始训练
十:使用matplotlib绘图查看结果
10.1:batch_size对于训练的影响
10.2:评估结果
总结
首先,下载fer2013数据集,
网址:https://www.kaggle.com/datasets/deadskull7/fer2013
使用pandas读取csv
import numpy as np
import pandas as pd
data = pd.read_csv('D:/code/fer2013.csv')
num_of_instances = len(data)#获取数据集的数量
print("数据集的数量为:",num_of_instances)
pixels = data['pixels']
emotions = data['emotion']
usages = data['Usage']
使用csv查看其中某一张照片
import cv2
img0 = list(map(eval,pixels[0].split(' ')))
np_img0 = np.asarray(img0)
img0 = np_img0.reshape(48,48)
import matplotlib.pyplot as plt
plt.imshow(img0,cmap = "gray")
划分数据集
emotions_Str = ['anger','disgust','fear','happy','neutral','sad','surprised']
from tensorflow.keras.utils import to_categorical
from PIL import Image
import os
num_classes = 7 #表情的类别数目
x_train,y_train,x_val,y_val,x_test,y_test = [],[],[],[],[],[]
from tqdm import tqdm
for i in tqdm(range(num_of_instances)):
usages_name = usages[i]
emotions_Str_Nmae = emotions_Str[emotions[i]]
one_hot_label = to_categorical(emotions[i],num_classes) #标签转换为one-hot编码,以满足keras对于数据的要求
img = list(map(eval,pixels[i].split(' ')))
np_img = np.asarray(img)
img = np_img.reshape(48,48)
if usages[i] == 'Training':
x_train.append(img)
y_train.append(one_hot_label)
elif usages[i] == 'PrivateTest':
x_val.append(img)
y_val.append(one_hot_label)
else:
x_test.append(img)
y_test.append(one_hot_label)
subfolder = os.path.join('D:/code/')
if not os.path.exists(subfolder):
os.makedirs(subfolder)
im = Image.fromarray(img).convert('L')
im.save(os.path.join(subfolder , (str(i)+'.jpg') ))
将数据转换为数组(array)格式,否则keras会报错
len(x_train)
x_train = np.array(x_train)
y_train = np.array(y_train)
x_train = x_train.reshape(-1,48,48,1)
x_test = np.array(x_test)
y_test = np.array(y_test)
x_test = x_test.reshape(-1,