VGG19实现fer2013人脸表情识别代码
时间: 2023-07-30 20:07:29 浏览: 152
基于TensorFlow+CNN+fer2013实现的人脸表情识别源码+详细代码注释.zip
5星 · 资源好评率100%
以下是使用VGG19模型实现FER2013人脸表情识别的Python代码示例:
```python
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.applications.vgg19 import VGG19
# 加载数据
df = pd.read_csv('fer2013.csv')
# 将数据拆分为训练、验证和测试集
train_data = df[df['Usage'] == 'Training']
val_data = df[df['Usage'] == 'PublicTest']
test_data = df[df['Usage'] == 'PrivateTest']
# 创建数据生成器
train_datagen = ImageDataGenerator(rescale=1./255,
rotation_range=10,
width_shift_range=0.1,
height_shift_range=0.1,
shear_range=0.1,
zoom_range=0.1,
horizontal_flip=True,
fill_mode='nearest')
val_datagen = ImageDataGenerator(rescale=1./255)
test_datagen = ImageDataGenerator(rescale=1./255)
# 定义批量大小和图像大小
batch_size = 32
img_size = (48, 48)
# 创建数据流
train_generator = train_datagen.flow_from_dataframe(train_data,
x_col='pixels',
y_col='emotion',
target_size=img_size,
batch_size=batch_size,
class_mode='categorical')
val_generator = val_datagen.flow_from_dataframe(val_data,
x_col='pixels',
y_col='emotion',
target_size=img_size,
batch_size=batch_size,
class_mode='categorical')
test_generator = test_datagen.flow_from_dataframe(test_data,
x_col='pixels',
y_col='emotion',
target_size=img_size,
batch_size=batch_size,
class_mode='categorical')
# 加载预训练的VGG19模型
base_model = VGG19(input_shape=(48, 48, 3), include_top=False, weights='imagenet')
# 冻结预训练模型的所有层
for layer in base_model.layers:
layer.trainable = False
# 添加自定义的分类层
x = base_model.output
x = tf.keras.layers.Flatten()(x)
x = tf.keras.layers.Dense(256, activation='relu')(x)
x = tf.keras.layers.Dropout(0.5)(x)
predictions = tf.keras.layers.Dense(7, activation='softmax')(x)
# 构建新模型
model = tf.keras.models.Model(inputs=base_model.input, outputs=predictions)
# 编译模型
model.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
# 训练模型
history = model.fit(train_generator,
steps_per_epoch=len(train_data) // batch_size,
epochs=50,
validation_data=val_generator,
validation_steps=len(val_data) // batch_size)
# 评估模型
test_loss, test_acc = model.evaluate(test_generator, verbose=2)
print('\nTest accuracy:', test_acc)
```
在这个示例中,我们使用了VGG19模型作为基础模型,并添加了自定义的分类层。我们还使用了预训练的权重,并冻结了所有预训练模型的层,只训练自定义分类层。这个模型可以用于FER2013数据集的人脸表情识别任务,并达到较高的准确率。
阅读全文