プリンキピア

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

3.5.1. Defining the Model3.5.1 モデルの定義

When we implemented linear regression from scratch in Section 3.4, we defined our model parameters explicitly and coded up the calculations to produce output using basic linear algebra operations. You should know how to do this. But once your models get more complex, and once you have to do this nearly every day, you will be glad of the assistance. The situation is similar to coding up your own blog from scratch. Doing it once or twice is rewarding and instructive, but you would be a lousy web developer if you spent a month reinventing the wheel.
英語のヒント
3.4節で線形回帰をゼロから実装したときは、モデルのパラメータを明示的に定義し、基本的な線形代数の演算を使って出力を出す計算を書いた。これはできるようにしておくべきである。しかし、モデルが複雑になり、これをほぼ毎日しなければならなくなると、手助けがありがたくなる。状況は、自分のブログをゼロから書くのに似ている。1度か2度やるのは得るものが多く勉強になるが、車輪の再発明に1か月を費やしていたら、ひどいWeb開発者だということになる。
For standard operations, we can use a framework’s predefined layers, which allow us to focus on the layers used to construct the model rather than worrying about their implementation. Recall the architecture of a single-layer network as described in Fig. 3.1.2. The layer is called fully connected, since each of its inputs is connected to each of its outputs by means of a matrix–vector multiplication.
英語のヒント
標準的な演算については、フレームワークがあらかじめ定義している層を使える。そうすれば、層の実装を気にするのではなく、モデルを組み立てるのに使う層に集中できる。図3.1.2で述べた単層ネットワークのアーキテクチャを思い出そう。この層は全結合と呼ばれる。行列とベクトルの積によって、各入力が各出力につながっているからである。
In PyTorch, the fully connected layer is defined in Linear and LazyLinear classes (available since version 1.8.0). The latter allows users to specify merely the output dimension, while the former additionally asks for how many inputs go into this layer. Specifying input shapes is inconvenient and may require nontrivial calculations (such as in convolutional layers). Thus, for simplicity, we will use such “lazy” layers whenever we can.
英語のヒント
PyTorchでは、全結合層はLinearクラスとLazyLinearクラス(バージョン1.8.0から利用可能)で定義されている。後者では利用者は出力の次元だけを指定すればよく、前者ではさらに、この層に入る入力の数も求められる。入力の形状を指定するのは不便で、(畳み込み層などでは)自明でない計算が必要になることもある。そこで単純さのために、できるかぎりこうした「遅延」層を使う。
class LinearRegression(d2l.Module):  #@save
    """The linear regression model implemented with high-level APIs."""
    def __init__(self, lr):
        super().__init__()
        self.save_hyperparameters()
        self.net = nn.LazyLinear(1)
        self.net.weight.data.normal_(0, 0.01)
        self.net.bias.data.fill_(0)
In the forward method we just invoke the built-in __call__ method of the predefined layers to compute the outputs.
英語のヒント
forwardメソッドでは、あらかじめ定義された層の組み込みの__call__メソッドを呼び出して、出力を計算するだけである。
@d2l.add_to_class(LinearRegression)  #@save
def forward(self, X):
    return self.net(X)