请优化 此代码,使他能完全实现人脸身份识别功能
时间: 2023-08-16 21:07:14 浏览: 192
好的,下面是一个使用卷积神经网络实现人脸身份识别的 Python 代码示例:
```python
import tensorflow as tf
from tensorflow.keras import layers, models, regularizers
from tensorflow.keras.preprocessing.image import ImageDataGenerator
# 数据集路径
train_dir = 'train'
validation_dir = 'validation'
# 图像大小
img_width = 150
img_height = 150
# 训练和验证的批量大小
batch_size = 32
# 数据增强
train_datagen = ImageDataGenerator(rescale=1./255, rotation_range=20, width_shift_range=0.2, height_shift_range=0.2, shear_range=0.2, zoom_range=0.2, horizontal_flip=True)
validation_datagen = ImageDataGenerator(rescale=1./255)
# 加载数据集
train_generator = train_datagen.flow_from_directory(train_dir, target_size=(img_width, img_height), batch_size=batch_size, class_mode='categorical')
validation_generator = validation_datagen.flow_from_directory(validation_dir, target_size=(img_width, img_height), batch_size=batch_size, class_mode='categorical')
# 构建模型
model = models.Sequential()
model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(img_width, img_height, 3)))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(128, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(256, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Flatten())
model.add(layers.Dropout(0.5))
model.add(layers.Dense(512, activation='relu', kernel_regularizer=regularizers.l2(0.001)))
model.add(layers.Dense(train_generator.num_classes, activation='softmax'))
# 编译模型
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
# 训练模型
history = model.fit(train_generator, steps_per_epoch=train_generator.samples//train_generator.batch_size, epochs=30, validation_data=validation_generator, validation_steps=validation_generator.samples//validation_generator.batch_size)
# 评估模型
test_dir = 'test'
test_datagen = ImageDataGenerator(rescale=1./255)
test_generator = test_datagen.flow_from_directory(test_dir, target_size=(img_width, img_height), batch_size=batch_size, class_mode='categorical')
test_loss, test_acc = model.evaluate(test_generator, steps=test_generator.samples//test_generator.batch_size, verbose=2)
print(f'Test accuracy: {test_acc}')
```
这个代码示例使用了 TensorFlow 框架和 Keras API ,使用了数据增强技术,使用了 L2 正则化和 Dropout 技术来防止过拟合。模型构建了四个卷积层和两个全连接层,使用 softmax 作为激活函数进行训练和评估。使用了训练集、验证集和测试集进行了模型的训练和评估,并且输出了测试集的准确率。这个代码示例可以完全实现人脸身份识别的功能。
阅读全文