第14章コンピュータビジョン
14.2.2. Hot Dog Recognition14.2.2 ホットドッグの認識
Let’s demonstrate fine-tuning via a concrete case: hot dog recognition. We will fine-tune a ResNet model on a small dataset, which was pretrained on the ImageNet dataset. This small dataset consists of thousands of images with and without hot dogs. We will use the fine-tuned model to recognize hot dogs from images.
英語のヒント
具体的な例であるホットドッグの認識を通じて、微調整を実演しよう。ImageNetのデータセットで事前学習したResNetモデルを、小さなデータセットで微調整する。この小さなデータセットは、ホットドッグがある画像とない画像の数千枚からなる。微調整したモデルを使って、画像からホットドッグを認識する。
%matplotlib inline
import os
import torch
import torchvision
from torch import nn
from d2l import torch as d2l14.2.2.1. Reading the Dataset14.2.2.1 データセットを読む
The hot dog dataset we use was taken from online images. This dataset consists of 1400 positive-class images containing hot dogs, and as many negative-class images containing other foods. 1000 images of both classes are used for training and the rest are for testing.
英語のヒント
使うホットドッグのデータセットは、オンラインの画像から取ったものである。このデータセットは、ホットドッグを含む正クラスの画像1400枚と、ほかの食べ物を含む同じ数の負クラスの画像からなる。両方のクラスの1000枚を訓練に使い、残りをテストに使う。
After unzipping the downloaded dataset, we obtain two folders
hotdog/train and hotdog/test. Both folders have hotdog and not-hotdog subfolders, either of which contains images of the corresponding class.英語のヒント
ダウンロードしたデータセットを解凍すると、
hotdog/trainとhotdog/testの二つのフォルダが得られる。どちらのフォルダにもhotdogとnot-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...We create two instances to read all the image files in the training and testing datasets, respectively.
英語のヒント
訓練とテストのデータセットのすべての画像ファイルをそれぞれ読むため、二つのインスタンスを作る。
train_imgs = torchvision.datasets.ImageFolder(os.path.join(data_dir, 'train'))
test_imgs = torchvision.datasets.ImageFolder(os.path.join(data_dir, 'test'))The first 8 positive examples and the last 8 negative images are shown below. As you can see, the images vary in size and aspect ratio.
英語のヒント
最初の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);
During training, we first crop a random area of random size and random aspect ratio from the image, and then scale this area to a input image. During testing, we scale both the height and width of an image to 256 pixels, and then crop a central area as input. In addition, for the three RGB (red, green, and blue) color channels we standardize their values channel by channel. Concretely, the mean value of a channel is subtracted from each value of that channel and then the result is divided by the standard deviation of that channel.
英語のヒント
訓練のあいだは、まず画像からランダムな大きさとランダムな縦横比のランダムな領域を切り抜き、それからこの領域をの入力画像に拡大縮小する。テストのあいだは、画像の高さと幅をどちらも256画素に拡大縮小し、それから中央のの領域を切り抜いて入力とする。さらに、三つの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])14.2.2.2. Defining and Initializing the Model14.2.2.2 モデルの定義と初期化
We use ResNet-18, which was pretrained on the ImageNet dataset, as the source model. Here, we specify
pretrained=True to automatically download the pretrained model parameters. If this model is used for the first time, Internet connection is required for download.英語のヒント
ImageNetのデータセットで事前学習したResNet-18をソースモデルとして使う。ここでは、
pretrained=Trueと指定して、事前学習したモデルのパラメータを自動的にダウンロードする。このモデルを初めて使う場合は、ダウンロードのためにインターネット接続が必要である。pretrained_net = torchvision.models.resnet18(pretrained=True)The pretrained source model instance contains a number of feature layers and an output layer
fc. The main purpose of this division is to facilitate the fine-tuning of model parameters of all layers but the output layer. The member variable fc of source model is given below.英語のヒント
事前学習したソースモデルのインスタンスには、いくつかの特徴層と出力層
fcがある。この分け方の主な目的は、出力層以外のすべての層のモデルのパラメータを微調整しやすくすることである。ソースモデルのメンバー変数fcを下に示す。pretrained_net.fcLinear(in_features=512, out_features=1000, bias=True)As a fully connected layer, it transforms ResNet’s final global average pooling outputs into 1000 class outputs of the ImageNet dataset. We then construct a new neural network as the target model. It is defined in the same way as the pretrained source model except that its number of outputs in the final layer is set to the number of classes in the target dataset (rather than 1000).
英語のヒント
全結合層として、それはResNetの最後の大域平均プーリングの出力を、ImageNetのデータセットの1000クラスの出力に変換する。次に、新しいニューラルネットワークをターゲットモデルとして構築する。それは、最後の層の出力の数が(1000ではなく)ターゲットデータセットのクラス数に設定されている点を除けば、事前学習したソースモデルと同じように定義される。
In the code below, the model parameters before the output layer of the target model instance
finetune_net are initialized to model parameters of the corresponding layers from the source model. Since these model parameters were obtained via pretraining on ImageNet, they are effective. Therefore, we can only use a small learning rate to fine-tune such pretrained parameters. In contrast, model parameters in the output layer are randomly initialized and generally require a larger learning rate to be learned from scratch. Letting the base learning rate be , a learning rate of will be used to iterate the model parameters in the output layer.英語のヒント
下のコードでは、ターゲットモデルのインスタンス
finetune_netの出力層より前のモデルのパラメータを、ソースモデルの対応する層のモデルのパラメータで初期化する。これらのモデルのパラメータはImageNetでの事前学習で得られたものなので、効果的である。したがって、そうした事前学習したパラメータを微調整するには、小さな学習率しか使えない。対照的に、出力層のモデルのパラメータはランダムに初期化され、ゼロから学習するには一般にもっと大きな学習率が要る。基本の学習率をとし、出力層のモデルのパラメータを反復するのにの学習率を使う。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);14.2.2.3. Fine-Tuning the Model14.2.2.3 モデルの微調整
First, we define a training function
train_fine_tuning that uses fine-tuning so it can be called multiple times.英語のヒント
まず、何度も呼び出せるように、微調整を使う訓練関数
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)We set the base learning rate to a small value in order to fine-tune the model parameters obtained via pretraining. Based on the previous settings, we will train the output layer parameters of the target model from scratch using a learning rate ten times greater.
英語のヒント
事前学習で得たモデルのパラメータを微調整するため、基本の学習率を小さな値に設定する。前の設定にもとづき、ターゲットモデルの出力層のパラメータは、10倍大きい学習率を使ってゼロから訓練する。
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)]For comparison, we define an identical model, but initialize all of its model parameters to random values. Since the entire model needs to be trained from scratch, we can use a larger learning rate.
英語のヒント
比較のため、同一のモデルを定義するが、そのモデルのパラメータはすべてランダムな値に初期化する。モデル全体をゼロから訓練する必要があるので、もっと大きな学習率を使える。
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)]As we can see, the fine-tuned model tends to perform better for the same epoch because its initial parameter values are more effective.
英語のヒント
見てのとおり、微調整したモデルは、初期のパラメータの値がもっと効果的なので、同じエポックでよい性能を出す傾向がある。