第14章コンピュータビジョン
14.14.4. Fine-Tuning a Pretrained Model14.14.4 事前学習したモデルの微調整
Again, the dataset for this competition is a subset of the ImageNet dataset. Therefore, we can use the approach discussed in Section 14.2 to select a model pretrained on the full ImageNet dataset and use it to extract image features to be fed into a custom small-scale output network. High-level APIs of deep learning frameworks provide a wide range of models pretrained on the ImageNet dataset. Here, we choose a pretrained ResNet-34 model, where we simply reuse the input of this model’s output layer (i.e., the extracted features). Then we can replace the original output layer with a small custom output network that can be trained, such as stacking two fully connected layers. Different from the experiment in Section 14.2, the following does not retrain the pretrained model used for feature extraction. This reduces training time and memory for storing gradients.
英語のヒント
繰り返すが、このコンペティションのデータセットはImageNetのデータセットの部分集合である。したがって、14.2節で論じたやり方を使って、ImageNetのデータセット全体で事前学習したモデルを選び、それを使って画像の特徴を抽出し、カスタムの小規模な出力ネットワークに入れられる。深層学習のフレームワークの高水準のAPIは、ImageNetのデータセットで事前学習した幅広いモデルを提供している。ここでは事前学習したResNet-34モデルを選び、このモデルの出力層の入力(つまり抽出した特徴)をそのまま再利用する。それから、元の出力層を、二つの全結合層を積み重ねるような、訓練できる小さなカスタムの出力ネットワークに置き換えられる。14.2節の実験とは違って、以下では、特徴の抽出に使う事前学習したモデルを訓練し直さない。これにより、訓練時間と、勾配を格納するためのメモリが減る。
Recall that we standardized images using the means and standard deviations of the three RGB channels for the full ImageNet dataset. In fact, this is also consistent with the standardization operation by the pretrained model on ImageNet.
英語のヒント
ImageNetのデータセット全体についての三つのRGBチャネルの平均と標準偏差を使って画像を標準化したことを思い出そう。実際、これはImageNetで事前学習したモデルによる標準化の操作とも一致している。
def get_net(devices):
finetune_net = nn.Sequential()
finetune_net.features = torchvision.models.resnet34(pretrained=True)
# Define a new output network (there are 120 output categories)
finetune_net.output_new = nn.Sequential(nn.Linear(1000, 256),
nn.ReLU(),
nn.Linear(256, 120))
# Move the model to devices
finetune_net = finetune_net.to(devices[0])
# Freeze parameters of feature layers
for param in finetune_net.features.parameters():
param.requires_grad = False
return finetune_netBefore calculating the loss, we first obtain the input of the pretrained model’s output layer, i.e., the extracted feature. Then we use this feature as input for our small custom output network to calculate the loss.
英語のヒント
損失を計算する前に、まず事前学習したモデルの出力層の入力、つまり抽出した特徴を得る。それから、この特徴を小さなカスタムの出力ネットワークの入力として使い、損失を計算する。
loss = nn.CrossEntropyLoss(reduction='none')
def evaluate_loss(data_iter, net, devices):
l_sum, n = 0.0, 0
for features, labels in data_iter:
features, labels = features.to(devices[0]), labels.to(devices[0])
outputs = net(features)
l = loss(outputs, labels)
l_sum += l.sum()
n += labels.numel()
return l_sum / n