知乎视频www.zhihu.com获取案例链接、直播课件、数据集请访问数据酷客社区版块。
卷积神经网络是一类典型的处理网格型数据的深度学习结构,在图像和视频处理等领域得到了广泛的应用。本案例采用 Olivetti Faces 人脸数据集进行训练,使用 TensorFlow 构建一个深度卷积神经网络对人脸进行识别。我们发现数据增强能够显著降低总体损失,提升神经网络性能。
1 Olivetti Faces 数据集探索
Olivetti Faces 是由纽约大学整理的一个人脸数据集。原始数据库可从(http://www.cl.cam.ac.uk/research/dtg/attarchive/facedatabase.html)。 我们使用的是 Sklearn 提供的版本。该版本是纽约大学 Sam Roweis 的个人主页以 MATLAB 格式提供的。
数据集包括 40 个不同的对象,每个对象都有 10 个不同的人脸图像。对于某些对象,图像是在不同的时间、光线、面部表情(睁眼/闭眼、微笑/不微笑)和面部细节(眼镜/不戴眼镜)下拍摄。所有的图像都是在一个深色均匀的背景下拍摄的,被摄者处于直立的正面位置(可能有细微面部移动)。原始数据集图像大小为 $92 \times 112$,而 Roweis 版本图像大小为 $64 \times 64$。
首先使用 sklearn 的 datasets 模块在线获取 Olivetti Faces 数据集。
from sklearn.datasets import fetch_olivetti_faces
faces = fetch_olivetti_faces()
观察发现,该数据集包括四部分:
1)DESCR 主要介绍了数据的来源;
2)data 以一维向量的形式存储了数据集中的400张图像;
3)images 以二维矩阵的形式存储了数据集中的400张图像;
4)target 存储了数据集中400张图像的类别信息,类别分别为 0-39 。
下面进一步观察数据的结构与类型:
print("The shape of data:",faces.data.shape, "The data type of data:",type(faces.data))
print("The shape of images:",faces.images.shape, "The data type of images:",type(faces.images))
print("The shape of target:",faces.target.shape, "The data type of target:",type(faces.target))
The shape of data: (400, 4096) The data type of data:
The shape of images: (400, 64, 64) The data type of images:
The shape of target: (400,) The data type of target:
可见,数据都以 numpy.ndarray 形式存储。因为下一步我们希望搭建卷积神经网络来实现人脸识别,所以特征要用二维矩阵存储的图像,这样可以充分挖掘图像的结构信息。
随机选取部分人脸,使用 matshow 函数将其可视化。
import numpy as np
rndperm = np.random.permutation(len(faces.images)) #将数据的索引随机打乱
import matplotlib.pyplot as plt
%matplotlib inline
plt.gray()
fig = plt.figure(figsize=(9,4) )
for i in range(0,18):
ax = fig.add_subplot(3,6,i+1 )
plt.title(str(faces.target[rndperm[i]]))
ax.matshow(faces.images[rndperm[i],:])
plt.box(False) #去掉边框
plt.axis("off")#不显示坐标轴
plt.tight_layout()
< Figure size 432x288 with 0 Axes >
查看同一个人的不同人脸的特点。
labels = [2,11,6] #选取三个人
%matplotlib inline
plt.gray()
fig = plt.figure(figsize=(12,4) )
for i in range(0,3):
faces_labeli = faces.images[faces.target == labels[i]]
for j in range(0,10):
ax = fi