第14章コンピュータビジョン
14.11.5. Prediction14.11.5 予測
When predicting, we need to standardize the input image in each channel and transform the image into the four-dimensional input format required by the CNN.
英語のヒント
予測するときは、入力画像を各チャネルで標準化し、画像をCNNが必要とする4次元の入力形式に変換する必要がある。
def predict(img):
X = test_iter.dataset.normalize_image(img).unsqueeze(0)
pred = net(X.to(devices[0])).argmax(dim=1)
return pred.reshape(pred.shape[1], pred.shape[2])To visualize the predicted class of each pixel, we map the predicted class back to its label color in the dataset.
英語のヒント
各画素の予測したクラスを可視化するため、予測したクラスをデータセットのラベルの色に対応させて戻す。
def label2image(pred):
colormap = torch.tensor(d2l.VOC_COLORMAP, device=devices[0])
X = pred.long()
return colormap[X, :]Images in the test dataset vary in size and shape. Since the model uses a transposed convolutional layer with stride of 32, when the height or width of an input image is indivisible by 32, the output height or width of the transposed convolutional layer will deviate from the shape of the input image. In order to address this issue, we can crop multiple rectangular areas with height and width that are integer multiples of 32 in the image, and perform forward propagation on the pixels in these areas separately. Note that the union of these rectangular areas needs to completely cover the input image. When a pixel is covered by multiple rectangular areas, the average of the transposed convolution outputs in separate areas for this same pixel can be input to the softmax operation to predict the class.
英語のヒント
テストデータセットの画像は、大きさも形もまちまちである。モデルはストライド32の転置畳み込み層を使うので、入力画像の高さか幅が32で割り切れないと、転置畳み込み層の出力の高さか幅は入力画像の形状からずれる。この問題に対処するには、画像の中で高さと幅が32の整数倍である複数の長方形の領域を切り抜き、これらの領域の画素について別々に順伝播を行えばよい。これらの長方形の領域の和集合は入力画像を完全に覆う必要があることに注意してほしい。ある画素が複数の長方形の領域で覆われるときは、この同じ画素についての別々の領域での転置畳み込みの出力の平均を、ソフトマックスの演算に入力してクラスを予測できる。
For simplicity, we only read a few larger test images, and crop a area for prediction starting from the upper-left corner of an image. For these test images, we print their cropped areas, prediction results, and ground-truth row by row.
英語のヒント
簡単のため、大きめのテスト画像をいくつかだけ読み、画像の左上の角から始まるの領域を切り抜いて予測する。これらのテスト画像について、切り抜いた領域、予測の結果、正解を行ごとに出力する。
voc_dir = d2l.download_extract('voc2012', 'VOCdevkit/VOC2012')
test_images, test_labels = d2l.read_voc_images(voc_dir, False)
n, imgs = 4, []
for i in range(n):
crop_rect = (0, 0, 320, 480)
X = torchvision.transforms.functional.crop(test_images[i], *crop_rect)
pred = label2image(predict(X))
imgs += [X.permute(1,2,0), pred.cpu(),
torchvision.transforms.functional.crop(
test_labels[i], *crop_rect).permute(1,2,0)]
d2l.show_images(imgs[::3] + imgs[1::3] + imgs[2::3], 3, n, scale=2);