第7章畳み込みニューラルネットワーク
7.6.1. LeNet7.6.1 LeNet
At a high level, LeNet (LeNet-5) consists of two parts: (i) a convolutional encoder consisting of two convolutional layers; and (ii) a dense block consisting of three fully connected layers. The architecture is summarized in Fig. 7.6.1.
英語のヒント
大まかに言えば、LeNet(LeNet-5)は二つの部分からなる。(i)二つの畳み込み層からなる畳み込みのエンコーダ、(ii)三つの全結合層からなる密なブロックである。この構造を図7.6.1にまとめる。
Fig. 7.6.1図7.6.1
Data flow in LeNet. The input is a handwritten digit, the output is a probability over 10 possible outcomes.
英語のヒント
LeNetでのデータの流れ。入力は手書きの数字で、出力は10通りの結果にわたる確率である。
The basic units in each convolutional block are a convolutional layer, a sigmoid activation function, and a subsequent average pooling operation. Note that while ReLUs and max-pooling work better, they had not yet been discovered. Each convolutional layer uses a kernel and a sigmoid activation function. These layers map spatially arranged inputs to a number of two-dimensional feature maps, typically increasing the number of channels. The first convolutional layer has 6 output channels, while the second has 16. Each pooling operation (stride 2) reduces dimensionality by a factor of via spatial downsampling. The convolutional block emits an output with shape given by (batch size, number of channel, height, width).
英語のヒント
各畳み込みブロックの基本単位は、畳み込み層、シグモイド活性化関数、それに続く平均プーリングの演算である。ReLUや最大プーリングのほうがうまく働くが、それらはまだ見いだされていなかったことに注意してほしい。各畳み込み層は、のカーネルとシグモイド活性化関数を使う。これらの層は、空間的に並んだ入力を、何枚かの2次元の特徴マップに写し、ふつうはチャネルの数を増やす。最初の畳み込み層は6個の出力チャネルをもち、2番目は16個をもつ。の各プーリング演算(ストライド2)は、空間的なダウンサンプリングによって次元を分の1に減らす。畳み込みブロックは、形状が(バッチサイズ、チャネル数、高さ、幅)で与えられる出力を出す。
In order to pass output from the convolutional block to the dense block, we must flatten each example in the minibatch. In other words, we take this four-dimensional input and transform it into the two-dimensional input expected by fully connected layers: as a reminder, the two-dimensional representation that we desire uses the first dimension to index examples in the minibatch and the second to give the flat vector representation of each example. LeNet’s dense block has three fully connected layers, with 120, 84, and 10 outputs, respectively. Because we are still performing classification, the 10-dimensional output layer corresponds to the number of possible output classes.
英語のヒント
畳み込みブロックから密なブロックへ出力を渡すには、ミニバッチの各事例を平らにしなければならない。言い換えれば、この4次元の入力を受け取り、全結合層が期待する2次元の入力に変換する。念のため言えば、望む2次元の表現は、1番目の次元でミニバッチの事例を添え字付けし、2番目の次元で各事例の平らなベクトル表現を与えるものである。LeNetの密なブロックには、出力がそれぞれ120、84、10の三つの全結合層がある。まだ分類を行っているので、10次元の出力層は、とりうる出力クラスの数に対応する。
While getting to the point where you truly understand what is going on inside LeNet may have taken a bit of work, we hope that the following code snippet will convince you that implementing such models with modern deep learning frameworks is remarkably simple. We need only to instantiate a
Sequential block and chain together the appropriate layers, using Xavier initialization as introduced in Section 5.4.2.2.英語のヒント
LeNetの中で何が起きているかを本当に理解できるところまで来るには、少し手間がかかったかもしれないが、次のコード片を見れば、現代の深層学習のフレームワークでそうしたモデルを実装するのが驚くほど簡単だと納得してもらえるはずである。
Sequentialブロックをインスタンス化し、5.4.2.2節で紹介したXavierの初期化を使いながら、適切な層をつなぎ合わせるだけでよい。def init_cnn(module): #@save
"""Initialize weights for CNNs."""
if type(module) == nn.Linear or type(module) == nn.Conv2d:
nn.init.xavier_uniform_(module.weight)
class LeNet(d2l.Classifier): #@save
"""The LeNet-5 model."""
def __init__(self, lr=0.1, num_classes=10):
super().__init__()
self.save_hyperparameters()
self.net = nn.Sequential(
nn.LazyConv2d(6, kernel_size=5, padding=2), nn.Sigmoid(),
nn.AvgPool2d(kernel_size=2, stride=2),
nn.LazyConv2d(16, kernel_size=5), nn.Sigmoid(),
nn.AvgPool2d(kernel_size=2, stride=2),
nn.Flatten(),
nn.LazyLinear(120), nn.Sigmoid(),
nn.LazyLinear(84), nn.Sigmoid(),
nn.LazyLinear(num_classes))We have taken some liberty in the reproduction of LeNet insofar as we have replaced the Gaussian activation layer by a softmax layer. This greatly simplifies the implementation, not least due to the fact that the Gaussian decoder is rarely used nowadays. Other than that, this network matches the original LeNet-5 architecture.
英語のヒント
LeNetの再現にあたっては、ガウス活性化層をソフトマックス層で置き換えたという点で、多少の自由をとった。これにより実装は大幅に簡単になる。とりわけ、ガウスのデコーダは今日ではめったに使われないという事実があるからである。それ以外の点では、このネットワークは元のLeNet-5の構造と一致している。
Let’s see what happens inside the network. By passing a single-channel (black and white) image through the network and printing the output shape at each layer, we can inspect the model to ensure that its operations line up with what we expect from Fig. 7.6.2.
英語のヒント
ネットワークの中で何が起きているかを見てみよう。一つのチャネル(白黒)のの画像をネットワークに通し、各層での出力の形状を表示すれば、モデルを調べて、その演算が図7.6.2から期待されるものと合っていることを確かめられる。
Fig. 7.6.2図7.6.2
Compressed notation for LeNet-5.
英語のヒント
LeNet-5の簡略な表記。
@d2l.add_to_class(d2l.Classifier) #@save
def layer_summary(self, X_shape):
X = torch.randn(*X_shape)
for layer in self.net:
X = layer(X)
print(layer.__class__.__name__, 'output shape:\t', X.shape)
model = LeNet()
model.layer_summary((1, 1, 28, 28))Conv2d output shape: torch.Size([1, 6, 28, 28])
Sigmoid output shape: torch.Size([1, 6, 28, 28])
AvgPool2d output shape: torch.Size([1, 6, 14, 14])
Conv2d output shape: torch.Size([1, 16, 10, 10])
Sigmoid output shape: torch.Size([1, 16, 10, 10])
AvgPool2d output shape: torch.Size([1, 16, 5, 5])
Flatten output shape: torch.Size([1, 400])
Linear output shape: torch.Size([1, 120])
Sigmoid output shape: torch.Size([1, 120])
Linear output shape: torch.Size([1, 84])
Sigmoid output shape: torch.Size([1, 84])
Linear output shape: torch.Size([1, 10])Note that the height and width of the representation at each layer throughout the convolutional block is reduced (compared with the previous layer). The first convolutional layer uses two pixels of padding to compensate for the reduction in height and width that would otherwise result from using a kernel. As an aside, the image size of pixels in the original MNIST OCR dataset is a result of trimming two pixel rows (and columns) from the original scans that measured pixels. This was done primarily to save space (a 30% reduction) at a time when megabytes mattered.
英語のヒント
畳み込みブロック全体を通じて、各層での表現の高さと幅は(前の層と比べて)小さくなっていることに注意してほしい。最初の畳み込み層は、パディングがなければのカーネルを使うことで生じる高さと幅の減少を補うため、2画素のパディングを使う。余談だが、元のMNISTのOCRデータセットの画像の大きさが画素なのは、画素あった元のスキャン画像から、2画素分の行(と列)を切り落とした結果である。これは主に、メガバイトが問題になった時代に、容量を節約する(30%の削減)ために行われた。
In contrast, the second convolutional layer forgoes padding, and thus the height and width are both reduced by four pixels. As we go up the stack of layers, the number of channels increases layer-over-layer from 1 in the input to 6 after the first convolutional layer and 16 after the second convolutional layer. However, each pooling layer halves the height and width. Finally, each fully connected layer reduces dimensionality, finally emitting an output whose dimension matches the number of classes.
英語のヒント
これに対して、2番目の畳み込み層はパディングを使わないので、高さも幅も4画素ずつ小さくなる。層の積み重ねを上っていくにつれて、チャネルの数は層を重ねるごとに、入力での1から、最初の畳み込み層の後の6、2番目の畳み込み層の後の16へと増えていく。一方、各プーリング層は高さと幅を半分にする。最後に、各全結合層は次元を減らし、最終的にはクラスの数と次元が一致する出力を出す。