プリンキピア

第3章回帰のための線形ニューラルネットワーク

3.2.2. Models3.2.2 モデル

The Module class is the base class of all models we will implement. At the very least we need three methods. The first, __init__, stores the learnable parameters, the training_step method accepts a data batch to return the loss value, and finally, configure_optimizers returns the optimization method, or a list of them, that is used to update the learnable parameters. Optionally we can define validation_step to report the evaluation measures. Sometimes we put the code for computing the output into a separate forward method to make it more reusable.
英語のヒント
Moduleクラスは、これから実装するすべてのモデルの基底クラスである。少なくとも三つのメソッドが必要になる。一つ目の__init__は学習可能なパラメータを保存し、training_stepメソッドはデータのバッチを受け取って損失の値を返し、最後にconfigure_optimizersは、学習可能なパラメータの更新に使う最適化の手法、またはそのリストを返す。省略可能だが、評価の尺度を報告するためにvalidation_stepを定義することもできる。出力を計算するコードを別のforwardメソッドに入れて、再利用しやすくすることもある。
class Module(nn.Module, d2l.HyperParameters):  #@save
    """The base class of models."""
    def __init__(self, plot_train_per_epoch=2, plot_valid_per_epoch=1):
        super().__init__()
        self.save_hyperparameters()
        self.board = ProgressBoard()

    def loss(self, y_hat, y):
        raise NotImplementedError

    def forward(self, X):
        assert hasattr(self, 'net'), 'Neural network is defined'
        return self.net(X)

    def plot(self, key, value, train):
        """Plot a point in animation."""
        assert hasattr(self, 'trainer'), 'Trainer is not inited'
        self.board.xlabel = 'epoch'
        if train:
            x = self.trainer.train_batch_idx / \
                self.trainer.num_train_batches
            n = self.trainer.num_train_batches / \
                self.plot_train_per_epoch
        else:
            x = self.trainer.epoch + 1
            n = self.trainer.num_val_batches / \
                self.plot_valid_per_epoch
        self.board.draw(x, value.to(d2l.cpu()).detach().numpy(),
                        ('train_' if train else 'val_') + key,
                        every_n=int(n))

    def training_step(self, batch):
        l = self.loss(self(*batch[:-1]), batch[-1])
        self.plot('loss', l, train=True)
        return l

    def validation_step(self, batch):
        l = self.loss(self(*batch[:-1]), batch[-1])
        self.plot('loss', l, train=False)

    def configure_optimizers(self):
        raise NotImplementedError
You may notice that Module is a subclass of nn.Module, the base class of neural networks in PyTorch. It provides convenient features for handling neural networks. For example, if we define a forward method, such as forward(self, X), then for an instance a we can invoke this method by a(X). This works since it calls the forward method in the built-in __call__ method. You can find more details and examples about nn.Module in Section 6.1.
英語のヒント
Moduleが、PyTorchのニューラルネットワークの基底クラスであるnn.Moduleのサブクラスであることに気づくかもしれない。これは、ニューラルネットワークを扱うのに便利な機能を提供する。たとえば、forward(self, X)のようなforwardメソッドを定義すると、インスタンスaについて、このメソッドをa(X)で呼び出せる。これは、組み込みの__call__メソッドの中でforwardメソッドが呼ばれるからである。nn.Moduleについての詳細と例は6.1節にある。