目录
Python实例题
题目
实现思路
代码实现
代码解释
数据加载与预处理:
构建 CNN 模型:
模型编译:
模型训练:
模型评估:
可视化训练过程:
运行思路
注意事项
Python实例题
题目
神经网络实现人脸识别任务
实现思路
- 数据加载与预处理:加载
Olivetti
人脸数据集,将数据划分为训练集和测试集,并对图像数据进行归一化处理。 - 构建 CNN 模型:使用
Keras
构建一个卷积神经网络模型,包含卷积层、池化层、全连接层等。 - 模型编译与训练:选择合适的损失函数、优化器和评估指标,对模型进行编译,并使用训练数据进行训练。
- 模型评估:使用测试数据对训练好的模型进行评估,计算准确率等指标。
- 预测与可视化:使用训练好的模型对新的人脸图像进行预测,并可视化预测结果。
代码实现
import numpy as np
from sklearn.datasets import fetch_olivetti_faces
from sklearn.model_selection import train_test_split
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense
from tensorflow.keras.utils import to_categorical
import matplotlib.pyplot as plt# 加载 Olivetti 人脸数据集
data = fetch_olivetti_faces()
X = data.images
y = data.target# 数据预处理
X = X.reshape(-1, 64, 64, 1) # 调整图像形状以适应 CNN 输入
X = X / 255.0 # 归一化处理
y = to_categorical(y) # 对标签进行 one-hot 编码# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)# 构建 CNN 模型
model = Sequential([Conv2D(32, (3, 3), activation='relu', input_shape=(64, 64, 1)),MaxPooling2D((2, 2)),Conv2D(64, (3, 3), activation='relu'),MaxPooling2D((2, 2)),Conv2D(128, (3, 3), activation='relu'),MaxPooling2D((2, 2)),Flatten(),Dense(128, activation='relu'),Dense(40, activation='softmax') # 40 个类别,对应 40 个人
])# 模型编译
model.compile(optimizer='adam',loss='categorical_crossentropy',metrics=['accuracy'])# 模型训练
history = model.fit(X_train, y_train, epochs=10, batch_size=32, validation_data=(X_test, y_test))# 模型评估
test_loss, test_acc = model.evaluate(X_test, y_test)
print(f"测试集损失: {test_loss}, 测试集准确率: {test_acc}")# 可视化训练过程
plt.figure(figsize=(12, 4))
plt.subplot(1, 2, 1)
plt.plot(history.history['accuracy'], label='Training Accuracy')
plt.plot(history.history['val_accuracy'], label='Validation Accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend()plt.subplot(1, 2, 2)
plt.plot(history.history['loss'], label='Training Loss')
plt.plot(history.history['val_loss'], label='Validation Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()plt.show()
代码解释
-
数据加载与预处理:
- 使用
fetch_olivetti_faces
函数加载Olivetti
人脸数据集。 - 将图像数据的形状调整为
(样本数, 高度, 宽度, 通道数)
,并进行归一化处理。 - 对标签进行
one-hot
编码,以便用于多分类任务。
- 使用
-
构建 CNN 模型:
- 使用
Sequential
模型依次添加卷积层、池化层、全连接层。 - 卷积层用于提取图像特征,池化层用于降低特征图的维度,全连接层用于进行分类。
- 使用
-
模型编译:
- 选择
adam
优化器,categorical_crossentropy
作为损失函数,accuracy
作为评估指标。
- 选择
-
模型训练:
- 使用
fit
方法对模型进行训练,指定训练数据、训练轮数、批次大小和验证数据。
- 使用
-
模型评估:
- 使用
evaluate
方法对训练好的模型进行评估,计算测试集的损失和准确率。
- 使用
-
可视化训练过程:
- 使用
matplotlib
绘制训练过程中的准确率和损失曲线,以便观察模型的训练情况。
- 使用
运行思路
- 安装依赖库:确保已经安装了
tensorflow
、scikit-learn
和matplotlib
库,可以使用以下命令进行安装:
pip install tensorflow scikit-learn matplotlib
- 运行脚本:将上述代码保存为
face_recognition_cnn.py
文件,在终端中运行:
python face_recognition_cnn.py
- 查看结果:脚本运行完成后,会输出测试集的损失和准确率,并显示训练过程中的准确率和损失曲线。
注意事项
- 模型复杂度:可以根据实际情况调整模型的层数、滤波器数量等参数,以提高模型的性能。
- 数据量:
Olivetti
人脸数据集相对较小,可能会导致模型过拟合。可以考虑使用数据增强技术或更大的数据集来提高模型的泛化能力。 - 训练时间:训练 CNN 模型可能需要较长的时间,尤其是在数据集较大或模型较复杂的情况下。可以使用 GPU 加速训练过程。