基于卷积神经网络的人脸表情识别代码
时间: 2023-07-25 13:03:43 浏览: 108
以下是基于卷积神经网络的人脸表情识别的代码:
```python
import numpy as np
import pandas as pd
import keras
from keras.layers import Conv2D, MaxPooling2D, Dense, Flatten, Dropout
from keras.models import Sequential
# 加载数据
data = pd.read_csv("fer2013.csv")
# 将像素值转换为图像
def string_to_image(string):
return np.array([int(x) for x in string.split()]).reshape(48, 48, 1) / 255.0
# 将数据转换为图像数据
data['image'] = data['pixels'].apply(string_to_image)
# 将标签转换为独热编码
def emotion_to_vector(emotion):
if emotion == 0:
return [1, 0, 0, 0, 0, 0, 0]
elif emotion == 1:
return [0, 1, 0, 0, 0, 0, 0]
elif emotion == 2:
return [0, 0, 1, 0, 0, 0, 0]
elif emotion == 3:
return [0, 0, 0, 1, 0, 0, 0]
elif emotion == 4:
return [0, 0, 0, 0, 1, 0, 0]
elif emotion == 5:
return [0, 0, 0, 0, 0, 1, 0]
elif emotion == 6:
return [0, 0, 0, 0, 0, 0, 1]
data['emotion_vec'] = data['emotion'].apply(emotion_to_vector)
# 划分训练集、验证集和测试集
train_data = data[data['Usage'] == 'Training'][['image', 'emotion_vec']]
val_data = data[data['Usage'] == 'PrivateTest'][['image', 'emotion_vec']]
test_data = data[data['Usage'] == 'PublicTest'][['image', 'emotion_vec']]
# 建立模型
model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=(48, 48, 1)))
model.add(Conv2D(64, kernel_size=(3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Conv2D(128, kernel_size=(3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(128, kernel_size=(3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(1024, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(7, activation='softmax'))
# 编译模型
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
# 训练模型
history = model.fit(np.array([x for x in train_data['image']]), np.array([x for x in train_data['emotion_vec']]),
validation_data=(np.array([x for x in val_data['image']]), np.array([x for x in val_data['emotion_vec']])),
epochs=50, batch_size=128)
# 评估模型
score = model.evaluate(np.array([x for x in test_data['image']]), np.array([x for x in test_data['emotion_vec']]), verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
```
这段代码使用了Keras库来建立卷积神经网络模型,使用FER2013数据集进行训练和测试,实现人脸表情识别功能。
阅读全文