第8章現代の畳み込みニューラルネットワーク
8.5.5. Concise Implementation8.5.5 簡潔な実装
Compared with the
BatchNorm class, which we just defined ourselves, we can use the BatchNorm class defined in high-level APIs from the deep learning framework directly. The code looks virtually identical to our implementation above, except that we no longer need to provide additional arguments for it to get the dimensions right.英語のヒント
自分で定義したばかりの
BatchNormクラスの代わりに、深層学習のフレームワークの高水準APIで定義されたBatchNormクラスを直接使える。コードは上の実装と実質的に同じに見えるが、次元を正しく得るために追加の引数を与える必要がもうない点だけが違う。class BNLeNet(d2l.Classifier):
def __init__(self, lr=0.1, num_classes=10):
super().__init__()
self.save_hyperparameters()
self.net = nn.Sequential(
nn.LazyConv2d(6, kernel_size=5), nn.LazyBatchNorm2d(),
nn.Sigmoid(), nn.AvgPool2d(kernel_size=2, stride=2),
nn.LazyConv2d(16, kernel_size=5), nn.LazyBatchNorm2d(),
nn.Sigmoid(), nn.AvgPool2d(kernel_size=2, stride=2),
nn.Flatten(), nn.LazyLinear(120), nn.LazyBatchNorm1d(),
nn.Sigmoid(), nn.LazyLinear(84), nn.LazyBatchNorm1d(),
nn.Sigmoid(), nn.LazyLinear(num_classes))Below, we use the same hyperparameters to train our model. Note that as usual, the high-level API variant runs much faster because its code has been compiled to C++ or CUDA while our custom implementation must be interpreted by Python.
英語のヒント
以下では、同じハイパーパラメータを使ってモデルを訓練する。いつものように、高水準APIの版のほうがずっと速く動くことに注意してほしい。そのコードはC++やCUDAにコンパイルされているが、独自の実装はPythonで解釈されなければならないからである。
trainer = d2l.Trainer(max_epochs=10, num_gpus=1)
data = d2l.FashionMNIST(batch_size=128)
model = BNLeNet(lr=0.1)
model.apply_init([next(iter(data.get_dataloader(True)))[0]], d2l.init_cnn)
trainer.fit(model, data)