第3章回帰のための線形ニューラルネットワーク
3.4.1. Defining the Model3.4.1 モデルの定義
Before we can begin optimizing our model’s parameters by minibatch SGD, we need to have some parameters in the first place. In the following we initialize weights by drawing random numbers from a normal distribution with mean 0 and a standard deviation of 0.01. The magic number 0.01 often works well in practice, but you can specify a different value through the argument
sigma. Moreover we set the bias to 0. Note that for object-oriented design we add the code to the __init__ method of a subclass of d2l.Module (introduced in Section 3.2.2).英語のヒント
ミニバッチSGDでモデルのパラメータの最適化を始める前に、そもそもパラメータが必要である。以下では、平均0、標準偏差0.01の正規分布から乱数を取り出して重みを初期化する。魔法の数0.01は実際にはうまくいくことが多いが、引数
sigmaで別の値を指定できる。さらに、バイアスを0にする。オブジェクト指向設計のために、コードをd2l.Module(3.2.2節で紹介した)のサブクラスの__init__メソッドに加えることに注意してほしい。class LinearRegressionScratch(d2l.Module): #@save
"""The linear regression model implemented from scratch."""
def __init__(self, num_inputs, lr, sigma=0.01):
super().__init__()
self.save_hyperparameters()
self.w = torch.normal(0, sigma, (num_inputs, 1), requires_grad=True)
self.b = torch.zeros(1, requires_grad=True)Next we must define our model, relating its input and parameters to its output. Using the same notation as (3.1.4) for our linear model we simply take the matrix–vector product of the input features and the model weights , and add the offset to each example. The product is a vector and is a scalar. Because of the broadcasting mechanism (see Section 2.1.4), when we add a vector and a scalar, the scalar is added to each component of the vector. The resulting
forward method is registered in the LinearRegressionScratch class via add_to_class (introduced in Section 3.2.1).英語のヒント
@d2l.add_to_class(LinearRegressionScratch) #@save
def forward(self, X):
return torch.matmul(X, self.w) + self.b