14.2. 微调
在 Colab 中打开 Notebook
在 Colab 中打开 Notebook
在 Colab 中打开 Notebook
在 Colab 中打开 Notebook
在 SageMaker Studio Lab 中打开 Notebook

在前面的章节中,我们讨论了如何在只有6万张图像的Fashion-MNIST训练数据集上训练模型。我们还描述了ImageNet,这是学术界最广泛使用的大规模图像数据集,它有超过1000万张图像和1000个物体。然而,我们通常遇到的数据集的大小介于这两个数据集之间。

假设我们想从图像中识别不同类型的椅子,然后向用户推荐购买链接。一种可能的方法是首先识别100把常见的椅子,为每把椅子拍摄1000张不同角度的图像,然后在收集到的图像数据集上训练一个分类模型。虽然这个椅子数据集可能比Fashion-MNIST数据集大,但样本数量仍然不到ImageNet的十分之一。这可能会导致适合ImageNet的复杂模型在这个椅子数据集上出现过拟合。此外,由于训练样本数量有限,训练出的模型的准确性可能无法满足实际要求。

为了解决上述问题,一个显而易见的解决方案是收集更多的数据。然而,收集和标记数据可能需要花费大量的时间和金钱。例如,为了收集ImageNet数据集,研究人员花费了数百万美元的研究经费。虽然目前的数据收集成本已大幅降低,但这一成本仍不容忽视。

另一个解决方案是应用*迁移学习*(transfer learning),将从*源数据集*(source dataset)学到的知识迁移到*目标数据集*(target dataset)。例如,尽管ImageNet数据集中的大多数图像与椅子无关,但在该数据集上训练的模型可以提取更通用的图像特征,这有助于识别边缘、纹理、形状和物体组成。这些相似的特征也可能对识别椅子有效。

14.2.1. 步骤

在本节中,我们将介绍迁移学习中的一种常用技术:*微调*(fine-tuning)。如 图 14.2.1 所示,微调包括以下四个步骤:

  1. 在一个源数据集(例如ImageNet数据集)上预训练一个神经网络模型,即*源模型*。

  2. 创建一个新的神经网络模型,即*目标模型*。它复制源模型上除输出层外的所有模型设计及其参数。我们假设这些模型参数包含了从源数据集中学到的知识,并且这些知识也适用于目标数据集。我们还假设源模型的输出层与源数据集的标签密切相关;因此它不用于目标模型。

  3. 向目标模型添加一个输出层,其输出数量是目标数据集中的类别数。然后随机初始化该层的模型参数。

  4. 在目标数据集(例如椅子数据集)上训练目标模型。输出层将从头开始训练,而所有其他层的参数将基于源模型的参数进行微调。

../_images/finetune.svg

图 14.2.1 微调。

当目标数据集远小于源数据集时,微调有助于提高模型的泛化能力。

14.2.2. 热狗识别

让我们通过一个具体的案例来演示微调:热狗识别。我们将在一个小数据集上微调一个ResNet模型,该模型是在ImageNet数据集上预训练的。这个小数据集由数千张包含和不包含热狗的图像组成。我们将使用微调后的模型从图像中识别热狗。

%matplotlib inline
import os
import torch
import torchvision
from torch import nn
from d2l import torch as d2l
%matplotlib inline
import os
from mxnet import gluon, init, np, npx
from mxnet.gluon import nn
from d2l import mxnet as d2l

npx.set_np()

14.2.2.1. 读取数据集

我们使用的热狗数据集取自网络图像。该数据集由1400张包含热狗的正类图像和同样多的包含其他食物的负类图像组成。两个类别的1000张图像用于训练,其余用于测试。

解压下载的数据集后,我们得到两个文件夹 hotdog/trainhotdog/test。这两个文件夹都有 hotdognot-hotdog 子文件夹,每个子文件夹都包含相应类别的图像。

#@save
d2l.DATA_HUB['hotdog'] = (d2l.DATA_URL + 'hotdog.zip',
                         'fba480ffa8aa7e0febbb511d181409f899b9baa5')

data_dir = d2l.download_extract('hotdog')
Downloading ../data/hotdog.zip from http://d2l-data.s3-accelerate.amazonaws.com/hotdog.zip...
#@save
d2l.DATA_HUB['hotdog'] = (d2l.DATA_URL + 'hotdog.zip',
                         'fba480ffa8aa7e0febbb511d181409f899b9baa5')

data_dir = d2l.download_extract('hotdog')
Downloading ../data/hotdog.zip from http://d2l-data.s3-accelerate.amazonaws.com/hotdog.zip...

我们创建两个实例来分别读取训练和测试数据集中的所有图像文件。

train_imgs = torchvision.datasets.ImageFolder(os.path.join(data_dir, 'train'))
test_imgs = torchvision.datasets.ImageFolder(os.path.join(data_dir, 'test'))
train_imgs = gluon.data.vision.ImageFolderDataset(
    os.path.join(data_dir, 'train'))
test_imgs = gluon.data.vision.ImageFolderDataset(
    os.path.join(data_dir, 'test'))

下面显示了前8个正例和后8个负例图像。如您所见,图像的大小和宽高比各不相同。

hotdogs = [train_imgs[i][0] for i in range(8)]
not_hotdogs = [train_imgs[-i - 1][0] for i in range(8)]
d2l.show_images(hotdogs + not_hotdogs, 2, 8, scale=1.4);
../_images/output_fine-tuning_368659_30_0.png
hotdogs = [train_imgs[i][0] for i in range(8)]
not_hotdogs = [train_imgs[-i - 1][0] for i in range(8)]
d2l.show_images(hotdogs + not_hotdogs, 2, 8, scale=1.4);
[22:08:09] ../src/storage/storage.cc:196: Using Pooled (Naive) StorageManager for CPU
../_images/output_fine-tuning_368659_33_1.png

在训练期间,我们首先从图像中裁剪出随机大小和随机宽高比的随机区域,然后将该区域缩放为 \(224 \times 224\) 的输入图像。在测试期间,我们将图像的高度和宽度都缩放到256像素,然后裁剪出一个中心的 \(224 \times 224\) 区域作为输入。此外,对于三个RGB(红、绿、蓝)颜色通道,我们逐个通道地对其值进行*标准化*。具体来说,从该通道的每个值中减去该通道的平均值,然后将结果除以该通道的标准差。

# Specify the means and standard deviations of the three RGB channels to
# standardize each channel
normalize = torchvision.transforms.Normalize(
    [0.485, 0.456, 0.406], [0.229, 0.224, 0.225])

train_augs = torchvision.transforms.Compose([
    torchvision.transforms.RandomResizedCrop(224),
    torchvision.transforms.RandomHorizontalFlip(),
    torchvision.transforms.ToTensor(),
    normalize])

test_augs = torchvision.transforms.Compose([
    torchvision.transforms.Resize([256, 256]),
    torchvision.transforms.CenterCrop(224),
    torchvision.transforms.ToTensor(),
    normalize])
# Specify the means and standard deviations of the three RGB channels to
# standardize each channel
normalize = gluon.data.vision.transforms.Normalize(
    [0.485, 0.456, 0.406], [0.229, 0.224, 0.225])

train_augs = gluon.data.vision.transforms.Compose([
    gluon.data.vision.transforms.RandomResizedCrop(224),
    gluon.data.vision.transforms.RandomFlipLeftRight(),
    gluon.data.vision.transforms.ToTensor(),
    normalize])

test_augs = gluon.data.vision.transforms.Compose([
    gluon.data.vision.transforms.Resize(256),
    gluon.data.vision.transforms.CenterCrop(224),
    gluon.data.vision.transforms.ToTensor(),
    normalize])

14.2.2.2. 定义和初始化模型

我们使用在ImageNet数据集上预训练的ResNet-18作为源模型。在这里,我们指定 pretrained=True 来自动下载预训练的模型参数。如果首次使用此模型,则需要互联网连接进行下载。

pretrained_net = torchvision.models.resnet18(pretrained=True)

预训练的源模型实例包含许多特征层和一个输出层 fc。这种划分的主要目的是为了方便对除输出层外的所有层的模型参数进行微调。源模型的成员变量 fc 如下所示。

pretrained_net.fc
Linear(in_features=512, out_features=1000, bias=True)
pretrained_net = gluon.model_zoo.vision.resnet18_v2(pretrained=True)
Downloading /opt/mxnet/models/resnet18_v2-a81db45f.zip2fac831f-e7e6-40bb-987f-e037f3e8e5d3 from https://apache-mxnet.s3-accelerate.dualstack.amazonaws.com/gluon/models/resnet18_v2-a81db45f.zip...

预训练的源模型实例包含两个成员变量:featuresoutput。前者包含模型除输出层外的所有层,后者是模型的输出层。这种划分的主要目的是为了方便对除输出层外的所有层的模型参数进行微调。源模型的成员变量 output 如下所示。

pretrained_net.output
Dense(512 -> 1000, linear)

作为一个全连接层,它将ResNet的最终全局平均池化输出转换为ImageNet数据集的1000个类别输出。然后我们构建一个新的神经网络作为目标模型。它的定义方式与预训练的源模型相同,只是其最后一层的输出数量被设置为目标数据集中的类别数(而不是1000)。

在下面的代码中,目标模型实例 finetune_net 的输出层之前的模型参数被初始化为源模型相应层的模型参数。由于这些模型参数是通过在ImageNet上预训练获得的,因此它们是有效的。因此,我们只能使用一个小的学习率来*微调*这些预训练的参数。相反,输出层中的模型参数是随机初始化的,通常需要一个更大的学习率从头开始学习。设基础学习率为 \(\eta\),将使用 \(10\eta\) 的学习率来迭代输出层中的模型参数。

finetune_net = torchvision.models.resnet18(pretrained=True)
finetune_net.fc = nn.Linear(finetune_net.fc.in_features, 2)
nn.init.xavier_uniform_(finetune_net.fc.weight);
finetune_net = gluon.model_zoo.vision.resnet18_v2(classes=2)
finetune_net.features = pretrained_net.features
finetune_net.output.initialize(init.Xavier())
# The model parameters in the output layer will be iterated using a learning
# rate ten times greater
finetune_net.output.collect_params().setattr('lr_mult', 10)

14.2.2.3. 微调模型

首先,我们定义一个使用微调的训练函数 train_fine_tuning,以便可以多次调用它。

# If `param_group=True`, the model parameters in the output layer will be
# updated using a learning rate ten times greater
def train_fine_tuning(net, learning_rate, batch_size=128, num_epochs=5,
                      param_group=True):
    train_iter = torch.utils.data.DataLoader(torchvision.datasets.ImageFolder(
        os.path.join(data_dir, 'train'), transform=train_augs),
        batch_size=batch_size, shuffle=True)
    test_iter = torch.utils.data.DataLoader(torchvision.datasets.ImageFolder(
        os.path.join(data_dir, 'test'), transform=test_augs),
        batch_size=batch_size)
    devices = d2l.try_all_gpus()
    loss = nn.CrossEntropyLoss(reduction="none")
    if param_group:
        params_1x = [param for name, param in net.named_parameters()
             if name not in ["fc.weight", "fc.bias"]]
        trainer = torch.optim.SGD([{'params': params_1x},
                                   {'params': net.fc.parameters(),
                                    'lr': learning_rate * 10}],
                                lr=learning_rate, weight_decay=0.001)
    else:
        trainer = torch.optim.SGD(net.parameters(), lr=learning_rate,
                                  weight_decay=0.001)
    d2l.train_ch13(net, train_iter, test_iter, loss, trainer, num_epochs,
                   devices)
def train_fine_tuning(net, learning_rate, batch_size=128, num_epochs=5):
    train_iter = gluon.data.DataLoader(
        train_imgs.transform_first(train_augs), batch_size, shuffle=True)
    test_iter = gluon.data.DataLoader(
        test_imgs.transform_first(test_augs), batch_size)
    devices = d2l.try_all_gpus()
    net.collect_params().reset_ctx(devices)
    net.hybridize()
    loss = gluon.loss.SoftmaxCrossEntropyLoss()
    trainer = gluon.Trainer(net.collect_params(), 'sgd', {
        'learning_rate': learning_rate, 'wd': 0.001})
    d2l.train_ch13(net, train_iter, test_iter, loss, trainer, num_epochs,
                   devices)

我们将基础学习率设置为一个较小的值,以便*微调*通过预训练获得的模型参数。根据前面的设置,我们将使用十倍大的学习率从头开始训练目标模型的输出层参数。

train_fine_tuning(finetune_net, 5e-5)
loss 0.242, train acc 0.909, test acc 0.940
1062.4 examples/sec on [device(type='cuda', index=0), device(type='cuda', index=1)]
../_images/output_fine-tuning_368659_79_1.svg
train_fine_tuning(finetune_net, 0.01)
loss 0.255, train acc 0.923, test acc 0.944
368.7 examples/sec on [gpu(0), gpu(1)]
../_images/output_fine-tuning_368659_82_1.svg

为了进行比较,我们定义了一个相同的模型,但将其所有模型参数初始化为随机值。由于整个模型需要从头开始训练,我们可以使用更大的学习率。

scratch_net = torchvision.models.resnet18()
scratch_net.fc = nn.Linear(scratch_net.fc.in_features, 2)
train_fine_tuning(scratch_net, 5e-4, param_group=False)
loss 0.352, train acc 0.846, test acc 0.850
1525.4 examples/sec on [device(type='cuda', index=0), device(type='cuda', index=1)]
../_images/output_fine-tuning_368659_88_1.svg
scratch_net = gluon.model_zoo.vision.resnet18_v2(classes=2)
scratch_net.initialize(init=init.Xavier())
train_fine_tuning(scratch_net, 0.1)
loss 0.356, train acc 0.842, test acc 0.860
574.1 examples/sec on [gpu(0), gpu(1)]
../_images/output_fine-tuning_368659_91_1.svg

正如我们所看到的,微调模型在相同周期下往往表现更好,因为它的初始参数值更有效。

14.2.3. 总结

  • 迁移学习将从源数据集中学到的知识迁移到目标数据集。微调是迁移学习的一种常用技术。

  • 目标模型复制源模型除输出层外的所有模型设计及其参数,并根据目标数据集对这些参数进行微调。相比之下,目标模型的输出层需要从头开始训练。

  • 通常,微调参数使用较小的学习率,而从头开始训练输出层可以使用较大的学习率。

14.2.4. 练习

  1. 不断增加 finetune_net 的学习率。模型的准确性如何变化?

  2. 在对比实验中进一步调整 finetune_netscratch_net 的超参数。它们的准确性是否仍然不同?

  3. finetune_net 输出层之前的参数设置为源模型的参数,并且在训练期间*不*更新它们。模型的准确性如何变化?您可以使用以下代码。

for param in finetune_net.parameters():
    param.requires_grad = False
finetune_net.features.collect_params().setattr('grad_req', 'null')
  1. 事实上,ImageNet 数据集中有一个“热狗”类别。其在输出层中对应的权重参数可以通过以下代码获得。我们如何利用这个权重参数?

weight = pretrained_net.fc.weight
hotdog_w = torch.split(weight.data, 1, dim=0)[934]
hotdog_w.shape
torch.Size([1, 512])

讨论

weight = pretrained_net.output.weight
hotdog_w = np.split(weight.data(), 1000, axis=0)[713]
hotdog_w.shape
(1, 512)

讨论