深度学习人脸表情识别代码
时间: 2023-07-28 15:08:09 浏览: 110
深度学习——人脸识别代码.rar
5星 · 资源好评率100%
以下是一个基于深度学习的人脸表情识别的Python代码示例:
```python
import numpy as np
import pandas as pd
import cv2
import keras
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout
from keras.preprocessing.image import ImageDataGenerator
# 加载数据集
train_data = pd.read_csv("fer2013/fer2013_train.csv")
test_data = pd.read_csv("fer2013/fer2013_test.csv")
# 数据预处理
train_pixels = train_data["pixels"].tolist()
train_images = []
for i in range(len(train_pixels)):
pixels = np.array(train_pixels[i].split())
image = pixels.reshape(48, 48, 1).astype("float32")
train_images.append(image)
train_images = np.array(train_images)
train_labels = keras.utils.to_categorical(train_data["emotion"], num_classes=7)
test_pixels = test_data["pixels"].tolist()
test_images = []
for i in range(len(test_pixels)):
pixels = np.array(test_pixels[i].split())
image = pixels.reshape(48, 48, 1).astype("float32")
test_images.append(image)
test_images = np.array(test_images)
test_labels = keras.utils.to_categorical(test_data["emotion"], num_classes=7)
# 构建模型
model = Sequential()
model.add(Conv2D(32, (3,3), activation="relu", input_shape=(48, 48, 1)))
model.add(Conv2D(64, (3,3), activation="relu"))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Dropout(0.25))
model.add(Conv2D(128, (3,3), activation="relu"))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Conv2D(128, (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(optimizer="adam", loss="categorical_crossentropy", metrics=["accuracy"])
# 数据增强
datagen = ImageDataGenerator(
rotation_range=15,
width_shift_range=0.1,
height_shift_range=0.1,
shear_range=0.1,
zoom_range=0.1,
horizontal_flip=True,
vertical_flip=False)
datagen.fit(train_images)
# 训练模型
history = model.fit_generator(datagen.flow(train_images, train_labels, batch_size=32),
steps_per_epoch=len(train_images) / 32, epochs=50, validation_data=(test_images, test_labels))
# 测试模型
test_loss, test_acc = model.evaluate(test_images, test_labels)
print("Test accuracy: ", test_acc)
# 保存模型
model.save("emotion_detection_model.h5")
```
这个示例代码使用Keras库搭建了一个卷积神经网络的模型,并使用FER2013数据集进行训练和测试,同时使用数据增强技术来提高模型的鲁棒性。最后,将模型保存到了本地文件中。
阅读全文