プリンキピア

第7章畳み込みニューラルネットワーク

7.2.4. Learning a Kernel7.2.4 カーネルを学習する

Designing an edge detector by finite differences [1, -1] is neat if we know this is precisely what we are looking for. However, as we look at larger kernels, and consider successive layers of convolutions, it might be impossible to specify precisely what each filter should be doing manually.
英語のヒント
有限差分[1, -1]で縁の検出器を設計するのは、それがまさに探しているものだとわかっていれば、すっきりしている。しかし、もっと大きなカーネルを見たり、畳み込みの層を何層も重ねたりすることを考えると、各フィルタが何をすべきかを手作業で正確に指定するのは不可能かもしれない。
Now let’s see whether we can learn the kernel that generated Y from X by looking at the input–output pairs only. We first construct a convolutional layer and initialize its kernel as a random tensor. Next, in each iteration, we will use the squared error to compare Y with the output of the convolutional layer. We can then calculate the gradient to update the kernel. For the sake of simplicity, in the following we use the built-in class for two-dimensional convolutional layers and ignore the bias.
英語のヒント
では、入力と出力の組だけを見て、XからYを生成したカーネルを学習できるかどうかを見てみよう。まず畳み込み層を作り、そのカーネルを無作為なテンソルとして初期化する。次に、各反復で、二乗誤差を使ってYを畳み込み層の出力と比べる。そうすれば、勾配を計算してカーネルを更新できる。簡単のため、以下では2次元の畳み込み層のための組み込みのクラスを使い、バイアスは無視する。
# Construct a two-dimensional convolutional layer with 1 output channel and a
# kernel of shape (1, 2). For the sake of simplicity, we ignore the bias here
conv2d = nn.LazyConv2d(1, kernel_size=(1, 2), bias=False)

# The two-dimensional convolutional layer uses four-dimensional input and
# output in the format of (example, channel, height, width), where the batch
# size (number of examples in the batch) and the number of channels are both 1
X = X.reshape((1, 1, 6, 8))
Y = Y.reshape((1, 1, 6, 7))
lr = 3e-2  # Learning rate

for i in range(10):
    Y_hat = conv2d(X)
    l = (Y_hat - Y) ** 2
    conv2d.zero_grad()
    l.sum().backward()
    # Update the kernel
    conv2d.weight.data[:] -= lr * conv2d.weight.grad
    if (i + 1) % 2 == 0:
        print(f'epoch {i + 1}, loss {l.sum():.3f}')
epoch 2, loss 16.481
epoch 4, loss 5.069
epoch 6, loss 1.794
epoch 8, loss 0.688
epoch 10, loss 0.274
Note that the error has dropped to a small value after 10 iterations. Now we will take a look at the kernel tensor we learned.
英語のヒント
10回の反復の後、誤差が小さな値まで下がったことに注意してほしい。では、学習したカーネルテンソルを見てみよう。
conv2d.weight.data.reshape((1, 2))
tensor([[ 1.0398, -0.9328]])
Indeed, the learned kernel tensor is remarkably close to the kernel tensor K we defined earlier.
英語のヒント
実際、学習したカーネルテンソルは、先ほど定義したカーネルテンソルKに驚くほど近い。