基于卷积神经网络的人脸识别的代码
时间: 2023-10-16 16:07:34 浏览: 214
以下是基于卷积神经网络的人脸识别的代码示例。
首先,我们需要导入必要的库和模块:
```python
import tensorflow as tf
from tensorflow.keras import layers
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, Activation, Flatten, Conv2D, MaxPooling2D
```
接下来,我们需要定义一些超参数,例如图像的高度和宽度、卷积核的大小、池化大小等:
```python
IMG_HEIGHT = 48
IMG_WIDTH = 48
NUM_CLASSES = 7
conv1_filters = 64
conv2_filters = 128
conv3_filters = 256
conv4_filters = 512
kernel_size = (3, 3)
pool_size = (2, 2)
input_shape = (IMG_HEIGHT, IMG_WIDTH, 1)
```
然后,我们需要加载数据集。这里我们使用Kaggle上的FER2013数据集,该数据集包含7个情感类别(愤怒、厌恶、恐惧、快乐、悲伤、惊讶和中性),每个类别有约3万张图像。
```python
# Load the dataset using pandas
import pandas as pd
df_train = pd.read_csv('train.csv')
df_test = pd.read_csv('test.csv')
num_train = len(df_train)
num_test = len(df_test)
print("Number of training samples: ", num_train)
print("Number of test samples: ", num_test)
```
我们接着需要对数据进行预处理。这里我们将图像的像素值归一化为[0,1]之间的浮点数,并将其转换为灰度图像。我们还需要将标签转换为类别矩阵:
```python
import numpy as np
# Preprocessing the data
X_train, y_train = [], []
for i in range(num_train):
X_train.append(np.array(df_train['pixels'][i].split(), dtype='float32').reshape(IMG_HEIGHT, IMG_WIDTH, 1) / 255.0)
y_train.append(df_train['emotion'][i])
X_test, y_test = [], []
for i in range(num_test):
X_test.append(np.array(df_test['pixels'][i].split(), dtype='float32').reshape(IMG_HEIGHT, IMG_WIDTH, 1) / 255.0)
y_test.append(df_test['emotion'][i])
X_train = np.array(X_train)
y_train = np.array(y_train)
X_test = np.array(X_test)
y_test = np.array(y_test)
# Convert labels to categorical one-hot encoding
y_train = tf.keras.utils.to_categorical(y_train, NUM_CLASSES)
y_test = tf.keras.utils.to_categorical(y_test, NUM_CLASSES)
```
接下来,我们需要构建卷积神经网络模型。这里我们采用了4个卷积层和2个全连接层。
```python
def build_model(input_shape):
model = Sequential()
# 1st convolutional layer
model.add(Conv2D(conv1_filters, kernel_size, padding='same', input_shape=input_shape))
model.add(Activation('relu'))
model.add(Conv2D(conv1_filters, kernel_size))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=pool_size))
model.add(Dropout(0.25))
# 2nd convolutional layer
model.add(Conv2D(conv2_filters, kernel_size, padding='same'))
model.add(Activation('relu'))
model.add(Conv2D(conv2_filters, kernel_size))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=pool_size))
model.add(Dropout(0.25))
# 3rd convolutional layer
model.add(Conv2D(conv3_filters, kernel_size, padding='same'))
model.add(Activation('relu'))
model.add(Conv2D(conv3_filters, kernel_size))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=pool_size))
model.add(Dropout(0.25))
# 4th convolutional layer
model.add(Conv2D(conv4_filters, kernel_size, padding='same'))
model.add(Activation('relu'))
model.add(Conv2D(conv4_filters, kernel_size))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=pool_size))
model.add(Dropout(0.25))
# Flatten the output layer to 1 dimension
model.add(Flatten())
# Fully connected layers
model.add(Dense(512))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(NUM_CLASSES))
model.add(Activation('softmax'))
return model
model = build_model(input_shape)
```
最后,我们需要编译并训练模型:
```python
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
model.fit(X_train, y_train, batch_size=64, epochs=50, validation_data=(X_test, y_test))
```
这里我们使用了交叉熵损失函数和Adam优化器,并在50个epoch上训练模型。
这是一个基本的人脸识别代码示例,你可以根据自己的需要进行修改和优化。
阅读全文