迁移学习 (Transfer Learning) 是机器学习中的一个重要研究方向,研究如何将在任务 A 上学到的知识迁移至任务 B,例如任务 A 为猫狗分类,任务 B 为牛马分类,任务 A 和任务 B 中存在大量的可共享知识,例如动物的毛发、体型、形态等。因此在任务 A 训练获得的模型已经掌握了这些知识,在训练任务 B 的模型时,可以不必从零开始训练,而是在任务 A 上获得的知识的基础上面进行训练或微调 (Fine-tuning)。和从零开始训练卷积神经网络相比,利用迁移学习,只需要少量样本即可训练得到性能较好的模型。
简单而言,迁移学习是指将一个预训练的模型重新用于另一个任务中。如下图所示,我们可以重用建立在不同数据集上的卷积神经网络,卷积层已经学习了图像中的各种特征(由于预训练模型使用了大量的图片,因此这些特征对于所有图像而言都具有极大程度上的通用性)。因此,网络的前面数层可以重用,网络后面的数层可以根据具体的任务设定从零开始训练,以便我们可以在新的数据集中预测图像类别。Keras 中提供了多个由不同研究人员提出的预训练模型,本文我们将使用预训练的 VGG16 模型利用迁移学习进行性别分类任务实战。
1.2 ImageNet 数据集介绍
在开始实战迁移学习之前,我们首先了解下 Keras 中集成的预训练模型所使用的数据集 ImageNet。ImageNet 是一项权威性的图像识别竞赛,要求参与者预测图像所属类别,数据集中有数百万个图像,其中包含尺寸不同的多种类别的图像。有大量的研究团队参与了此竞赛,他们提出了不同的神经网络模型预测图像类别。鉴于有数百万个图像,因此数据集中的数据量不成问题,同时研究团队为了获取优异的模型性能构建了庞大的神经网络网络体系,因此也解决了在前言中所述的第二个问题。
2. 利用预训练 VGG16 模型进行性别分类
该模型的架构与我们在《使用卷积神经网络实现性别分类》中训练的 CNN 模型类似,主要区别在于该模型更深,使用了更多的卷积、池化层,VGG16 网络的权重是通过对数百万个图像进行训练而获得的。
我们在使用预训练模型对图像中的人物进行性别分类时,确保冻结 VGG16 权重的更新。尺寸为 256x256x3 的图像通过 VGG16 网络后特征图形状为 8 x 8 x 512。我们将保持原始网络中的权重不变,得到 8 x 8 x 512 输出,之后将其通过另一个卷积池化操作,然后通过展平层后,连接到全连接层,然后使用 Sigmoid 激活函数确定图像中人物是男性还是女性。
本质上,通过使用 VGG16 模型的卷积和池化层,我们使用了在数以百万计的数据集上训练的卷积核。最终,我们为要预测的图片对象微调 (fine-tuning) 通过这些卷积和池化层得到的输出。
2.2 微调模型
本节中,我们使用 Keras 实现以上分析的迁移学习策略。首先,导入所需库以及预训练的 VGG16 模型。我们不使用 VGG16 模型中的最后一层,即 include_top=False,这是为了之后我们针对要解决的问题微调 VGG16 模型。另外,我们的指定输入图像形状为 256 X 256 X 3:
from keras.applications import VGG16
from keras.applications.vgg16 import preprocess_input
from glob import glob
from skimage import io
import cv2
import numpy as np
from sklearn.model_selection import train_test_split