プリンキピア

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

7.2.3. Object Edge Detection in Images7.2.3 画像の中の物体の縁の検出

Let’s take a moment to parse a simple application of a convolutional layer: detecting the edge of an object in an image by finding the location of the pixel change. First, we construct an “image” of 6×8 pixels. The middle four columns are black (0) and the rest are white (1).
英語のヒント
少し時間をとって、畳み込み層の簡単な応用を詳しく見てみよう。画素の変化する位置を見つけることで、画像の中の物体の縁を検出するのである。まず、6×8画素の「画像」を作る。真ん中の4列は黒(0)で、残りは白(1)である。
X = torch.ones((6, 8))
X[:, 2:6] = 0
X
tensor([[1., 1., 0., 0., 0., 0., 1., 1.],
        [1., 1., 0., 0., 0., 0., 1., 1.],
        [1., 1., 0., 0., 0., 0., 1., 1.],
        [1., 1., 0., 0., 0., 0., 1., 1.],
        [1., 1., 0., 0., 0., 0., 1., 1.],
        [1., 1., 0., 0., 0., 0., 1., 1.]])
Next, we construct a kernel K with a height of 1 and a width of 2. When we perform the cross-correlation operation with the input, if the horizontally adjacent elements are the same, the output is 0. Otherwise, the output is nonzero. Note that this kernel is a special case of a finite difference operator. At location (i,j) it computes xi,j−x(i+1),j, i.e., it computes the difference between the values of horizontally adjacent pixels. This is a discrete approximation of the first derivative in the horizontal direction. After all, for a function f(i,j) its derivative −∂if(i,j)=limϵ→0f(i,j)−f(i+ϵ,j)ϵ. Let’s see how this works in practice.
英語のヒント
次に、高さ1、幅2のカーネルKを作る。入力と相互相関の演算を行うとき、横に隣り合う要素が同じなら、出力は0になる。そうでなければ、出力は0でない。このカーネルは、有限差分の演算子の特別な場合であることに注意してほしい。位置(i,j)でxi,j−x(i+1),jを計算する。つまり、横に隣り合う画素の値の差を計算する。これは、横方向の1階導関数の離散的な近似である。何しろ、関数f(i,j)について、その導関数は−∂if(i,j)=limϵ→0f(i,j)−f(i+ϵ,j)ϵなのである。実際にこれがどう働くかを見てみよう。
K = torch.tensor([[1.0, -1.0]])
We are ready to perform the cross-correlation operation with arguments X (our input) and K (our kernel). As you can see, we detect 1 for the edge from white to black and −1 for the edge from black to white. All other outputs take value 0.
英語のヒント
引数X(入力)とK(カーネル)で相互相関の演算を行う準備ができた。見てのとおり、白から黒への縁では1が、黒から白への縁では−1が検出される。ほかの出力はすべて値0をとる。
Y = corr2d(X, K)
Y
tensor([[ 0.,  1.,  0.,  0.,  0., -1.,  0.],
        [ 0.,  1.,  0.,  0.,  0., -1.,  0.],
        [ 0.,  1.,  0.,  0.,  0., -1.,  0.],
        [ 0.,  1.,  0.,  0.,  0., -1.,  0.],
        [ 0.,  1.,  0.,  0.,  0., -1.,  0.],
        [ 0.,  1.,  0.,  0.,  0., -1.,  0.]])
We can now apply the kernel to the transposed image. As expected, it vanishes. The kernel K only detects vertical edges.
英語のヒント
今度は、転置した画像にカーネルを当てはめてみる。予想どおり、出力は消える。カーネルKは縦の縁しか検出しないのである。
corr2d(X.t(), K)
tensor([[0., 0., 0., 0., 0.],
        [0., 0., 0., 0., 0.],
        [0., 0., 0., 0., 0.],
        [0., 0., 0., 0., 0.],
        [0., 0., 0., 0., 0.],
        [0., 0., 0., 0., 0.],
        [0., 0., 0., 0., 0.],
        [0., 0., 0., 0., 0.]])