20.2  微调

前面的一些章节介绍了如何在只有 6 万张图像的 Fashion-MNIST 训练数据集上训练模型。我们还描述了学术界当下使用最广泛的大规模图像数据集 ImageNet,它有超过 1000 万的图像和 1000 类的物体。然而,我们平常接触到的数据集的规模通常在这两者之间。

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

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

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

20.2.1 步骤

本节将介绍迁移学习中的常见技巧:微调(fine-tuning)。如 图 20.2.1 所示,微调包括以下四个步骤。

  1. 在源数据集(例如 ImageNet 数据集)上预训练神经网络模型,即源模型。
  2. 创建一个新的神经网络模型,即目标模型。这将复制源模型上的所有模型设计及其参数(输出层除外)。我们假定这些模型参数包含从源数据集中学到的知识,这些知识也将适用于目标数据集。我们还假设源模型的输出层与源数据集的标签密切相关;因此不在目标模型中使用该层。
  3. 向目标模型添加输出层,其输出数是目标数据集中的类别数。然后随机初始化该层的模型参数。
  4. 在目标数据集(如椅子数据集)上训练目标模型。输出层将从头开始进行训练,而所有其他层的参数将根据源模型的参数进行微调。
图 20.2.1: 微调。

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

20.2.2 热狗识别

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

import os
import torchvision
import keras
import os
import os
import tensorflow as tf
from d2l.nnx_resnet import Bottleneck, ResNet50
import os
# Activation (gradient) checkpointing. Fine-tuning ResNet-50 at batch size 128
# would otherwise hold the whole forward graph's activations live for the
# backward pass (~23 GB). Wrapping each residual block (`Bottleneck`) in
# `nnx.remat` recomputes that block's activations during backprop instead of
# storing them, cutting the peak to ~6 GB. `nnx.remat` propagates state
# correctly, so gradients and batch-norm running statistics are identical to
# the un-checkpointed model.
if not getattr(Bottleneck, '_d2l_remat', False):
    Bottleneck.__call__ = nnx.remat(Bottleneck.__call__)
    Bottleneck._d2l_remat = True

20.2.2.1 获取数据集

我们使用的数据集采集自网络图像:该热狗数据集包含 1400 张含有热狗的正类图像,以及同样数量含有其他食物的负类图像。两个类别各有 1000 张图像用于训练,其余用于测试。

解压下载的数据集,我们获得了两个文件夹 hotdog/train 和 hotdog/test。这两个文件夹都有 hotdog(有热狗)和 not-hotdog(无热狗)两个子文件夹,子文件夹内都包含相应类的图像。

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

data_dir = d2l.download_extract('hotdog')

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

train_imgs = torchvision.datasets.ImageFolder(os.path.join(data_dir, 'train'))
test_imgs = torchvision.datasets.ImageFolder(os.path.join(data_dir, 'test'))
from PIL import Image as _PILImage
import pathlib

def _load_image_folder(path):
    """Load images from a directory with class subfolders, returning
    a list of (PIL.Image, class_index) tuples."""
    path = pathlib.Path(path)
    class_names = sorted([p.name for p in path.iterdir() if p.is_dir()])
    class_to_idx = {c: i for i, c in enumerate(class_names)}
    items = []
    for cls in class_names:
        for img_path in sorted((path / cls).iterdir()):
            try:
                img = _PILImage.open(str(img_path)).convert('RGB')
                items.append((img, class_to_idx[cls]))
            except Exception:
                continue
    return items

train_imgs = _load_image_folder(os.path.join(data_dir, 'train'))
test_imgs = _load_image_folder(os.path.join(data_dir, 'test'))
# Load images as (PIL.Image, label) lists for compatibility with show_images
from PIL import Image as _PILImage
import pathlib

def _load_image_folder(path):
    """Load images from a directory with class subfolders, returning
    a list of (PIL.Image, class_index) tuples."""
    path = pathlib.Path(path)
    class_names = sorted([p.name for p in path.iterdir() if p.is_dir()])
    class_to_idx = {c: i for i, c in enumerate(class_names)}
    items = []
    for cls in class_names:
        for img_path in sorted((path / cls).iterdir()):
            try:
                img = _PILImage.open(str(img_path)).convert('RGB')
                items.append((img, class_to_idx[cls]))
            except Exception:
                continue
    return items

train_imgs = _load_image_folder(os.path.join(data_dir, 'train'))
test_imgs = _load_image_folder(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);

在训练期间,我们首先从图像中裁切随机大小和随机长宽比的区域,然后将该区域缩放为 \(224 \times 224\) 输入图像。在测试过程中,我们将图像的高度和宽度都缩放到 256 像素,然后裁剪中央 \(224 \times 224\) 区域作为输入。此外,对于 RGB(红、绿和蓝)颜色通道,我们分别标准化每个通道。具体而言,该通道的每个值减去该通道的平均值,然后将结果除以该通道的标准差。

图像在加载时先调整为 \(256 \times 256\) 像素,因此训练裁剪是在不重新缩放的情况下直接截取固定大小与宽高比的 \(224 \times 224\) 随机窗口。这里不做标准差归一化,而是调用 Keras 的 resnet50.preprocess_input 将 RGB 转为 BGR 并减去 ImageNet 通道均值(不除以标准差),以匹配预训练 Keras 权重所要求的输入约定。

图像在加载时先调整为 \(256 \times 256\) 像素,因此训练裁剪是在不重新缩放的情况下直接截取固定大小与宽高比的 \(224 \times 224\) 随机窗口。

# 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])
# Plain tf.image / tf.data preprocessing for Keras ResNet50 (NHWC). Keras
# ResNet50 expects its own `preprocess_input` convention, not an RGB
# mean/std normalization.
IMG_SIZE = 224

def _normalize(x):
    return tf.keras.applications.resnet50.preprocess_input(
        tf.cast(x, tf.float32))

def train_augs(x, training=False):
    # Input is (256, 256, 3) — already resized by image_dataset_from_directory.
    x = tf.image.random_crop(x, (IMG_SIZE, IMG_SIZE, 3))
    x = tf.image.random_flip_left_right(x)
    return _normalize(x)

def test_augs(x, training=False):
    # Input is (256, 256, 3) — already resized by image_dataset_from_directory.
    # Center crop to IMG_SIZE x IMG_SIZE.
    off = (256 - IMG_SIZE) // 2
    x = x[off:off + IMG_SIZE, off:off + IMG_SIZE, :]
    return _normalize(x)
# Image preprocessing. We use `tf.image` ops so the pipeline can run
# inside `tf.data.Dataset.map`. The ImageNet RGB mean/std normalization
# matches the preprocessing expected by the pretrained ImageNet ResNet
# weights.
IMG_SIZE = 224
_IMAGENET_MEAN = tf.constant([0.485, 0.456, 0.406], dtype=tf.float32)
_IMAGENET_STD  = tf.constant([0.229, 0.224, 0.225], dtype=tf.float32)

def _normalize(x):
    return (tf.cast(x, tf.float32) / 255.0 - _IMAGENET_MEAN) / _IMAGENET_STD

def train_preprocess(x):
    # `x` is a (256, 256, 3) float32 RGB image with values in [0, 255].
    x = tf.image.random_crop(x, size=(IMG_SIZE, IMG_SIZE, 3))
    x = tf.image.random_flip_left_right(x)
    return _normalize(x)

def test_preprocess(x):
    x = tf.image.resize_with_crop_or_pad(x, IMG_SIZE, IMG_SIZE)
    return _normalize(x)
# 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])

20.2.2.2 定义和初始化模型

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

我们使用在 ImageNet 数据集上预训练的 ResNet-50 作为源模型(Keras 3 的 keras.applications 未内置预训练 ResNet-18,因此这里改用 ResNet-50),指定 weights='imagenet' 自动下载预训练模型参数。首次使用时需连接互联网下载。

我们使用在 ImageNet 上预训练的 NNX ResNet-50 作为源模型,从 Hugging Face 下载官方 Microsoft safetensors 权重并直接映射载入有状态的 NNX 模型。首次使用时需连接互联网下载。

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

pretrained_net = torchvision.models.resnet18(
    weights=torchvision.models.ResNet18_Weights.DEFAULT)
# Load pretrained ResNet50 (full model with top) to inspect the output layer
pretrained_net = keras.applications.ResNet50(weights='imagenet')
_dummy = jnp.zeros((1, IMG_SIZE, IMG_SIZE, 3), dtype=jnp.float32)
pretrained_net = ResNet50.from_pretrained()
pretrained_net = gluon.model_zoo.vision.resnet18_v2(pretrained=True)

预训练的源模型实例包含许多特征层和一个输出层 fc。此划分的主要目的是促进对除输出层以外所有层的模型参数进行微调。下面给出了源模型的成员变量 fc。

来自 keras.applications 的预训练 ResNet50 包含若干特征提取层和一个输出层,我们将复用这些预训练权重进行迁移学习。下面查看源模型的最后一层。

预训练源模型由卷积主干网络和最后的 fc 层(1000 类 ImageNet 分类器)组成。这样划分主要是为了方便微调除输出层以外所有层的模型参数。下面打印源模型分类器权重的形状。

预训练的源模型实例包含两个成员变量:features 和 output。前者包含除输出层以外的模型的所有层,后者是模型的输出层。此划分的主要目的是促进对除输出层以外所有层的模型参数进行微调。源模型的成员变量 output 如下所示。

pretrained_net.fc
Linear(in_features=512, out_features=1000, bias=True)
pretrained_net.layers[-1]
<Dense name=predictions, built=True>
pretrained_net.fc.kernel.shape
(2048, 1000)
pretrained_net.output
Dense(512 -> 1000, linear)

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

在下面的代码中,目标模型实例 finetune_net 输出层之前的模型参数被初始化为源模型对应层的参数。由于这些模型参数已在 ImageNet 上预训练过、本身十分有效,我们只需使用较小的学习率对这些预训练参数进行微调;相反,输出层中的模型参数是随机初始化的,通常需要更大的学习率从头学习。设基础学习率为 \(\eta\),则采用 \(10\eta\) 的学习率迭代更新输出层参数。

finetune_net = torchvision.models.resnet18(
    weights=torchvision.models.ResNet18_Weights.DEFAULT)
finetune_net.fc = nn.Linear(finetune_net.fc.in_features, 2)
nn.init.xavier_uniform_(finetune_net.fc.weight);
# Pretrained ResNet50 base (no top) + global average pool + fresh 2-class head
finetune_net = keras.Sequential([
    keras.applications.ResNet50(weights='imagenet', include_top=False,
                                pooling='avg',
                                input_shape=(IMG_SIZE, IMG_SIZE, 3)),
    keras.layers.Dense(2, kernel_initializer='glorot_uniform',
                       name='classifier'),
])
finetune_net = ResNet50.from_pretrained()
finetune_net.fc = nnx.Linear(2048, 2, rngs=nnx.Rngs(1))
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
for p in finetune_net.output.collect_params().values():
    p.lr_mult = 10

20.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 _make_tf_dataset(img_dir, augs, batch_size, shuffle=False):
    """Create a tf.data.Dataset from an image folder using Keras pipelines."""
    ds = keras.utils.image_dataset_from_directory(
        img_dir, label_mode='int', image_size=(256, 256),
        batch_size=None, shuffle=shuffle)
    ds = ds.map(lambda x, y: (augs(x, training=True), y),
                num_parallel_calls=tf.data.AUTOTUNE)
    ds = ds.batch(batch_size).prefetch(tf.data.AUTOTUNE)
    return ds

def _checkpointed_backbone(base):
    """Run the ResNet50 convolutional backbone with per-residual-block
    activation checkpointing. A plain `tf.GradientTape` over ResNet-50 at batch
    size 128 keeps every layer's activations live for the backward pass (~22 GB
    of GPU memory). Splitting the backbone into its 16 residual blocks and
    wrapping each in `tf.recompute_grad` recomputes a block's activations during
    backprop instead of storing them, dropping the peak to a few GB. The
    gradients are unchanged -- activations are simply traded for a little extra
    compute. Returns a callable `fn(x, training) -> 2048-d pooled features`."""
    boundaries = ['pool1_pool'] + [l.name for l in base.layers
                                   if l.name.endswith('_out')]
    segments = [keras.Model(base.input, base.get_layer(boundaries[0]).output)]
    for a, b in zip(boundaries[:-1], boundaries[1:]):
        segments.append(keras.Model(base.get_layer(a).output,
                                    base.get_layer(b).output))
    pool = keras.layers.GlobalAveragePooling2D()
    def forward(x, training=False):
        h = x
        for seg in segments:
            h = tf.recompute_grad(
                lambda t, seg=seg: seg(t, training=training))(h)
        return pool(h)
    return forward

# If `param_group=True`, the head (classifier Dense) learns ten times
# faster than the backbone. `momentum` is forwarded to both SGD optimizers; the
# from-scratch baseline uses momentum=0.9 because plain SGD cannot train a
# randomly-initialised ResNet-50 on 2 000 images in five epochs.
def train_fine_tuning(net, learning_rate, batch_size=128, num_epochs=5,
                      param_group=True, momentum=0.0):
    train_ds = _make_tf_dataset(os.path.join(data_dir, 'train'),
                                train_augs, batch_size, shuffle=True)
    test_ds  = _make_tf_dataset(os.path.join(data_dir, 'test'),
                                test_augs, batch_size, shuffle=False)
    # Backbone always trainable; discriminative LR (head at 10x) applied
    # by routing gradients to two separate optimizers below.
    net.layers[0].trainable = True
    # Running averages of the batch statistics decay 0.9 per step (the
    # Keras default is 0.99). tf.recompute_grad runs the forward pass twice
    # per step, so the averages update twice: 0.9 ** 0.5 per update
    for layer in net.layers[0].layers:
        if isinstance(layer, keras.layers.BatchNormalization):
            layer.momentum = 0.9 ** 0.5
    head_layer = net.layers[-1]
    head_vars = head_layer.trainable_variables
    head_var_ids = {id(v) for v in head_vars}
    # Activation-checkpointed backbone (see `_checkpointed_backbone`); the
    # classifier head is applied to its pooled features. Training still runs
    # over `net.trainable_variables`, so the discriminative-LR split is intact.
    backbone = _checkpointed_backbone(net.layers[0])

    opt_head = keras.optimizers.SGD(
        learning_rate=learning_rate * (10 if param_group else 1),
        momentum=momentum, weight_decay=0.001)
    opt_base = keras.optimizers.SGD(
        learning_rate=learning_rate,
        momentum=momentum, weight_decay=0.001)
    loss_fn = keras.losses.SparseCategoricalCrossentropy(from_logits=True)
    acc_metric = keras.metrics.SparseCategoricalAccuracy()
    val_acc_metric = keras.metrics.SparseCategoricalAccuracy()

    @tf.function
    def train_step(x, y):
        with tf.GradientTape() as tape:
            logits = head_layer(backbone(x, training=True))
            loss = loss_fn(y, logits)
        grads = tape.gradient(loss, net.trainable_variables)
        head_pairs, base_pairs = [], []
        for g, v in zip(grads, net.trainable_variables):
            if g is None:
                continue
            (head_pairs if id(v) in head_var_ids
             else base_pairs).append((g, v))
        if head_pairs:
            opt_head.apply_gradients(head_pairs)
        if base_pairs:
            opt_base.apply_gradients(base_pairs)
        acc_metric.update_state(y, logits)
        return loss

    @tf.function
    def test_step(x, y):
        logits = net(x, training=False)
        val_acc_metric.update_state(y, logits)

    for epoch in range(num_epochs):
        acc_metric.reset_state()
        val_acc_metric.reset_state()
        total_loss, n_train = 0.0, 0
        for x, y in train_ds:  # Weight each minibatch by its size
            total_loss += float(train_step(x, y)) * len(y); n_train += len(y)
        for x, y in test_ds:
            test_step(x, y)
        print(f'epoch {epoch + 1}, loss {total_loss / max(n_train, 1):.3f}, '
              f'train acc {float(acc_metric.result()):.3f}, '
              f'test acc {float(val_acc_metric.result()):.3f}')
def _make_tf_dataset(img_dir, preprocess, batch_size, shuffle=False):
    """Create a tf.data.Dataset from an image folder directory."""
    ds = tf.keras.utils.image_dataset_from_directory(
        img_dir, label_mode='int', image_size=(256, 256),
        batch_size=None, shuffle=shuffle)
    ds = ds.map(lambda x, y: (preprocess(x), y),
                num_parallel_calls=tf.data.AUTOTUNE)
    ds = ds.batch(batch_size).prefetch(tf.data.AUTOTUNE)
    return ds

# If `param_group=True`, the head learns ten times faster than the
# pretrained backbone; otherwise all parameters are trained at the same rate
# (used for `scratch_net`).
def train_fine_tuning(net, learning_rate, batch_size=128, num_epochs=5,
                      param_group=True, update_batch_stats=False,
                      momentum=0.0):
    train_ds = _make_tf_dataset(os.path.join(data_dir, 'train'),
                                train_preprocess, batch_size, shuffle=True)
    test_ds = _make_tf_dataset(os.path.join(data_dir, 'test'),
                               test_preprocess, batch_size, shuffle=False)

    # Per-parameter learning rate: 10x for the new classifier, 1x for the
    # pretrained backbone. Use a label tree to drive optax.multi_transform.
    # Weight decay and optional momentum follow the comparison recipes below.
    if param_group:
        def labels(params):
            return jax.tree_util.tree_map_with_path(
                lambda path, _: ('head' if any(
                    (getattr(p, 'key', None) == 'fc' or
                     getattr(p, 'name', None) == 'fc') for p in path)
                                 else 'base'), params)
        tx = optax.multi_transform(
            {'head': optax.chain(
                 optax.add_decayed_weights(0.001),
                 optax.sgd(learning_rate * 10, momentum=momentum)),
             'base': optax.chain(
                 optax.add_decayed_weights(0.001),
                 optax.sgd(learning_rate, momentum=momentum))},
            labels)
    else:
        tx = optax.chain(
            optax.add_decayed_weights(0.001),
            optax.sgd(learning_rate, momentum=momentum))
    optimizer = nnx.Optimizer(net, tx, wrt=nnx.Param)
    train_net = nnx.view(net, use_running_average=not update_batch_stats,
                         raise_if_not_found=False)
    eval_net = nnx.view(net, use_running_average=True,
                        raise_if_not_found=False)

    @nnx.jit
    def train_step(model, optimizer, x, y):
        def loss_fn(model):
            logits = model(x)
            loss = optax.softmax_cross_entropy_with_integer_labels(
                logits, y).mean()
            return loss, logits
        (loss, logits), grads = nnx.value_and_grad(
            loss_fn, has_aux=True)(model)
        optimizer.update(model, grads)
        acc = (jnp.argmax(logits, axis=-1) == y).mean()
        return loss, acc

    @nnx.jit
    def eval_step(model, x, y):
        logits = model(x)
        return (jnp.argmax(logits, axis=-1) == y).sum()

    for epoch in range(num_epochs):
        total_loss, total_acc, n_train = jnp.array(0.0), jnp.array(0.0), 0
        for x, y in train_ds:
            x = jnp.asarray(x.numpy()); y = jnp.asarray(y.numpy())
            loss, acc = train_step(train_net, optimizer, x, y)
            total_loss += loss * len(y)  # Weight each minibatch by its size
            total_acc += acc * len(y)
            n_train += len(y)
        test_correct, test_examples = jnp.array(0), 0
        for x, y in test_ds:
            x = jnp.asarray(x.numpy()); y = jnp.asarray(y.numpy())
            test_correct += eval_step(eval_net, x, y)
            test_examples += len(y)
        total_loss, total_acc, test_correct = jax.device_get(
            (total_loss, total_acc, test_correct))
        print(f'epoch {epoch + 1}, loss {float(total_loss) / n_train:.3f}, '
              f'train acc {float(total_acc) / n_train:.3f}, '
              f'test acc {float(test_correct) / max(test_examples, 1):.3f}')

    return net
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.reset_device(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.257, train acc 0.920, test acc 0.919
1495.0 examples/sec on [device(type='cuda', index=0)]

train_fine_tuning(finetune_net, 5e-5, momentum=0.9)
Found 2000 files belonging to 2 classes.
Found 800 files belonging to 2 classes.
epoch 1, loss 0.653, train acc 0.651, test acc 0.756
epoch 2, loss 0.400, train acc 0.825, test acc 0.854
epoch 3, loss 0.288, train acc 0.882, test acc 0.877
epoch 4, loss 0.240, train acc 0.909, test acc 0.896
epoch 5, loss 0.216, train acc 0.924, test acc 0.904
print('fine-tuned model')
finetune_net = train_fine_tuning(finetune_net, 1e-4, momentum=0.9)
fine-tuned model
Found 2000 files belonging to 2 classes.
Found 800 files belonging to 2 classes.
epoch 1, loss 0.636, train acc 0.781, test acc 0.877
epoch 2, loss 0.515, train acc 0.913, test acc 0.914
epoch 3, loss 0.406, train acc 0.935, test acc 0.919
epoch 4, loss 0.328, train acc 0.942, test acc 0.921
epoch 5, loss 0.273, train acc 0.945, test acc 0.927
# lr divided by batch_size: gluon Trainer no longer rescales (issue 7 fix in d2l.train_batch_ch13)
train_fine_tuning(finetune_net, 7.8125e-5)
loss 0.263, train acc 0.919, test acc 0.940
460.1 examples/sec on [gpu(0)]

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

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.363, train acc 0.849, test acc 0.843
1699.9 examples/sec on [device(type='cuda', index=0)]

# Train from scratch: same architecture but with random (no-pretrain) weights.
scratch_base = keras.applications.ResNet50(
    weights=None, include_top=False, pooling='avg',
    input_shape=(IMG_SIZE, IMG_SIZE, 3))
scratch_net = keras.Sequential([
    scratch_base,
    keras.layers.Dense(2, kernel_initializer='glorot_uniform',
                       name='classifier'),
])
# Plain SGD (momentum=0) cannot train a randomly-initialised ResNet-50 on
# 2 000 images in five epochs, so we use SGD with momentum=0.9 and a single
# uniform learning rate (no head/backbone split) for the from-scratch run.
train_fine_tuning(scratch_net, 1e-3, param_group=False, momentum=0.9)
Found 2000 files belonging to 2 classes.
Found 800 files belonging to 2 classes.
epoch 1, loss 0.715, train acc 0.553, test acc 0.484
epoch 2, loss 0.642, train acc 0.630, test acc 0.614
epoch 3, loss 0.553, train acc 0.730, test acc 0.798
epoch 4, loss 0.412, train acc 0.818, test acc 0.729
epoch 5, loss 0.394, train acc 0.832, test acc 0.814
print('scratch baseline')
scratch_net = ResNet50(num_classes=2, rngs=nnx.Rngs(2))
scratch_net = train_fine_tuning(
    scratch_net, 1e-3, num_epochs=6, param_group=False,
    update_batch_stats=True, momentum=0.9)
scratch baseline
Found 2000 files belonging to 2 classes.
Found 800 files belonging to 2 classes.
epoch 1, loss 0.700, train acc 0.526, test acc 0.497
epoch 2, loss 0.627, train acc 0.676, test acc 0.517
epoch 3, loss 0.557, train acc 0.718, test acc 0.785
epoch 4, loss 0.441, train acc 0.798, test acc 0.755
epoch 5, loss 0.434, train acc 0.817, test acc 0.794
epoch 6, loss 0.404, train acc 0.834, test acc 0.772
scratch_net = gluon.model_zoo.vision.resnet18_v2(classes=2)
scratch_net.initialize(init=init.Xavier())
# lr divided by batch_size: gluon Trainer no longer rescales (issue 7 fix in d2l.train_batch_ch13)
train_fine_tuning(scratch_net, 7.8125e-4)
loss 0.340, train acc 0.857, test acc 0.829
547.2 examples/sec on [gpu(0)]

可以看到,微调模型在更少的训练轮数内就达到了较高的准确率,因为其初始参数值已经编码了有用的视觉特征。

20.2.3 小结

  • 迁移学习将从源数据集中学到的知识迁移到目标数据集,微调是迁移学习的常见技巧。
  • 除输出层外,目标模型从源模型中复制所有模型设计及其参数,并根据目标数据集对这些参数进行微调。但是,目标模型的输出层需要从头开始训练。
  • 通常,微调参数使用较小的学习率,而从头开始训练输出层可以使用更大的学习率。

20.2.4 练习

  1. 继续提高 finetune_net 的学习率,模型的准确性如何变化?
  2. 在比较实验中进一步调整 finetune_net 和 scratch_net 的超参数。它们的准确性还有不同吗?
  3. 将输出层 finetune_net 之前的参数设置为源模型的参数,在训练期间不要更新它们。模型的准确性如何变化?提示:可以使用以下代码。
for param in finetune_net.parameters():
    param.requires_grad = False
# Freeze the ResNet50 backbone (layer 0 of the Sequential); only head trains.
finetune_net.layers[0].trainable = False
# Freeze the pretrained ResNet-50 backbone; only the new `fc` head
# is updated by setting the optimizer learning rate of every other parameter
# to zero. For example, modify `train_fine_tuning` to use:
#   optax.multi_transform(
#       {'head': optax.sgd(lr * 10, momentum=0.9),
#        'base': optax.set_to_zero()},
#       labels)
for p in finetune_net.features.collect_params().values():
    p.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.layers[-1].get_weights()[0]  # Shape: (2048, 1000)
hotdog_w = weight[:, 934]
hotdog_w.shape
(2048,)
# The pretrained classifier maps 2048-dimensional features to 1000 classes.
weight = pretrained_net.fc.kernel[...]  # Shape: (2048, 1000)
hotdog_w = weight[:, 934]
hotdog_w.shape
(2048,)
weight = pretrained_net.output.weight
hotdog_w = mnp.split(weight.data(), 1000, axis=0)[713]
hotdog_w.shape
(1, 512)
  1. train_augs 使用了 RandomResizedCrop(224)(默认从 \([0.08, 1]\) 中均匀抽取裁剪面积占原图面积的比例 \(s\),再将裁剪区域缩放到 \(224 \times 224\) 像素),而 test_augs 则将图像缩放到 \(256 \times 256\) 像素并保留中心的 \(224 \times 224\) 像素。忽略裁剪时的随机宽高比,假设原图是边长为 \(L\) 的正方形。
    1. 证明原图中边长为 \(\ell\) 的物体在训练阶段呈现出的边长为 \(224\ell/(\sqrt{s}L)\),而在测试阶段呈现出的边长为 \(256\ell/L\)。
    2. 计算训练阶段与测试阶段物体表观尺寸之比的期望 \(\mathbb{E}_s[224/(256\sqrt{s})]\):在训练阶段物体在网络看来更大还是更小?相差多少倍?
    3. 若要在平均意义上消除这一尺度偏差,测试图像应先缩放到多大的边长 \(R\)?解释为什么 ResNet 无须修改任何网络结构即可接收更大尺寸的输入。
    4. 假设 train_augs 改为先将图像缩放到 \(256 \times 256\) 像素再随机截取 \(224 \times 224\) 窗口,还会存在上述尺度偏差吗?作为代价它会失去什么?
  1. 本节的 train_augs 从缩放到 \(256 \times 256\) 像素的图像中随机截取 \(224 \times 224\) 窗口,而 test_augs 保留同一缩放图像中心的 \(224 \times 224\) 像素。另一种常见做法(如 torchvision 中的 RandomResizedCrop(224))是从 \([0.08, 1]\) 中均匀抽取裁剪面积占原图面积的比例 \(s\),再将裁剪区域缩放到 \(224 \times 224\) 像素。忽略裁剪时的随机宽高比,假设原图是边长为 \(L\) 的正方形。
    1. 证明采用 RandomResizedCrop(224) 时,原图中边长为 \(\ell\) 的物体在训练阶段呈现出的边长为 \(224\ell/(\sqrt{s}L)\),而在测试阶段呈现出的边长为 \(256\ell/L\)。
    2. 计算训练阶段与测试阶段物体表观尺寸之比的期望 \(\mathbb{E}_s[224/(256\sqrt{s})]\):在训练阶段物体在网络看来更大还是更小?相差多少倍?
    3. 若要在平均意义上消除这一尺度偏差,测试图像应先缩放到多大的边长 \(R\)?解释为什么 ResNet 无须修改任何网络结构即可接收更大尺寸的输入。
    4. 本节所用的裁剪方案是否存在同样的尺度偏差?作为代价它放弃了什么?
  1. 本节的 train_augs 从缩放到 \(256 \times 256\) 像素的图像中随机截取 \(224 \times 224\) 窗口,而 test_augs 保留同一缩放图像中心的 \(224 \times 224\) 像素。另一种常见做法(如 torchvision 中的 RandomResizedCrop(224))是从 \([0.08, 1]\) 中均匀抽取裁剪面积占原图面积的比例 \(s\),再将裁剪区域缩放到 \(224 \times 224\) 像素。忽略裁剪时的随机宽高比,假设原图是边长为 \(L\) 的正方形。
    1. 证明采用 RandomResizedCrop(224) 时,原图中边长为 \(\ell\) 的物体在训练阶段呈现出的边长为 \(224\ell/(\sqrt{s}L)\),而在测试阶段呈现出的边长为 \(256\ell/L\)。
    2. 计算训练阶段与测试阶段物体表观尺寸之比的期望 \(\mathbb{E}_s[224/(256\sqrt{s})]\):在训练阶段物体在网络看来更大还是更小?相差多少倍?
    3. 若要在平均意义上消除这一尺度偏差,测试图像应先缩放到多大的边长 \(R\)?解释为什么 ResNet 无须修改任何网络结构即可接收更大尺寸的输入。
    4. 本节所用的裁剪方案是否存在同样的尺度偏差?作为代价它放弃了什么?
  1. train_augs 使用了 RandomResizedCrop(224)(默认从 \([0.08, 1]\) 中均匀抽取裁剪面积占原图面积的比例 \(s\),再将裁剪区域缩放到 \(224 \times 224\) 像素),而 test_augs 则将图像缩放到 \(256 \times 256\) 像素并保留中心的 \(224 \times 224\) 像素。忽略裁剪时的随机宽高比,假设原图是边长为 \(L\) 的正方形。
    1. 证明原图中边长为 \(\ell\) 的物体在训练阶段呈现出的边长为 \(224\ell/(\sqrt{s}L)\),而在测试阶段呈现出的边长为 \(256\ell/L\)。
    2. 计算训练阶段与测试阶段物体表观尺寸之比的期望 \(\mathbb{E}_s[224/(256\sqrt{s})]\):在训练阶段物体在网络看来更大还是更小?相差多少倍?
    3. 若要在平均意义上消除这一尺度偏差,测试图像应先缩放到多大的边长 \(R\)?解释为什么 ResNet 无须修改任何网络结构即可接收更大尺寸的输入。
    4. 假设 train_augs 改为先将图像缩放到 \(256 \times 256\) 像素再随机截取 \(224 \times 224\) 窗口,还会存在上述尺度偏差吗?作为代价它会失去什么?
  1. 目标数据集越小时,微调的优势理应越明显。请保持测试集不变,在每类包含 100、250、500 和 1000 张训练图像的类别平衡随机子集上,分别重新训练全新的 finetune_net 副本和 scratch_net 副本(对较小子集相应增大 num_epochs,使每次运行的小批量更新总步数与全量训练集大致相同)。在对数横轴上绘制两个模型的测试准确率随训练图像数量变化的曲线:scratch_net 每类需要多少张图像才能达到 finetune_net 仅用每类 100 张图像就能达到的准确率(如果在该范围内能够达到的话)?