プリンキピア

第5章多層パーセプトロン

5.2.1. Implementation from Scratch5.2.1 ゼロからの実装

Let’s begin again by implementing such a network from scratch.
英語のヒント
まずは再び、こうしたネットワークをゼロから実装することから始めよう。

5.2.1.1. Initializing Model Parameters5.2.1.1 モデルのパラメータの初期化

Recall that Fashion-MNIST contains 10 classes, and that each image consists of a 28×28=784 grid of grayscale pixel values. As before we will disregard the spatial structure among the pixels for now, so we can think of this as a classification dataset with 784 input features and 10 classes. To begin, we will implement an MLP with one hidden layer and 256 hidden units. Both the number of layers and their width are adjustable (they are considered hyperparameters). Typically, we choose the layer widths to be divisible by larger powers of 2. This is computationally efficient due to the way memory is allocated and addressed in hardware.
英語のヒント
Fashion-MNISTには10のクラスがあり、各画像はグレースケールの画素値の28×28=784の格子からなることを思い出してほしい。前と同じく、今のところは画素のあいだの空間的な構造は無視するので、これを784個の入力特徴量と10のクラスをもつ分類のデータセットと考えられる。まず、隠れ層が一つで隠れユニットが256個のMLPを実装する。層の数とその幅はどちらも調整できる(ハイパーパラメータとみなされる)。ふつうは、層の幅を2の大きなべき乗で割り切れるように選ぶ。ハードウェアでメモリが割り当てられ番地付けされるしくみのおかげで、そのほうが計算の効率がよいからである。
Again, we will represent our parameters with several tensors. Note that for every layer, we must keep track of one weight matrix and one bias vector. As always, we allocate memory for the gradients of the loss with respect to these parameters.
英語のヒント
ここでも、パラメータはいくつかのテンソルで表す。どの層についても、重み行列一つとバイアスベクトル一つを追跡しなければならないことに注意してほしい。いつものように、これらのパラメータについての損失の勾配のためのメモリを割り当てる。
In the code below we use nn.Parameter to automatically register a class attribute as a parameter to be tracked by autograd (Section 2.5).
英語のヒント
下のコードでは、nn.Parameterを使って、クラスの属性を、autograd(2.5節)に追跡されるパラメータとして自動的に登録する。
class MLPScratch(d2l.Classifier):
    def __init__(self, num_inputs, num_outputs, num_hiddens, lr, sigma=0.01):
        super().__init__()
        self.save_hyperparameters()
        self.W1 = nn.Parameter(torch.randn(num_inputs, num_hiddens) * sigma)
        self.b1 = nn.Parameter(torch.zeros(num_hiddens))
        self.W2 = nn.Parameter(torch.randn(num_hiddens, num_outputs) * sigma)
        self.b2 = nn.Parameter(torch.zeros(num_outputs))

5.2.1.2. Model5.2.1.2 モデル

To make sure we know how everything works, we will implement the ReLU activation ourselves rather than invoking the built-in relu function directly.
英語のヒント
すべてがどう動くかを確実に理解するため、組み込みのrelu関数を直接呼び出すのではなく、ReLU活性化を自分で実装する。
def relu(X):
    a = torch.zeros_like(X)
    return torch.max(X, a)
Since we are disregarding spatial structure, we reshape each two-dimensional image into a flat vector of length num_inputs. Finally, we implement our model with just a few lines of code. Since we use the framework built-in autograd this is all that it takes.
英語のヒント
空間的な構造は無視しているので、各2次元画像をreshapeで長さnum_inputsの平らなベクトルに変形する。最後に、ほんの数行のコードでモデルを実装する。フレームワークに組み込まれた自動微分を使うので、必要なのはこれだけである。
@d2l.add_to_class(MLPScratch)
def forward(self, X):
    X = X.reshape((-1, self.num_inputs))
    H = relu(torch.matmul(X, self.W1) + self.b1)
    return torch.matmul(H, self.W2) + self.b2

5.2.1.3. Training5.2.1.3 訓練

Fortunately, the training loop for MLPs is exactly the same as for softmax regression. We define the model, data, and trainer, then finally invoke the fit method on model and data.
英語のヒント
幸い、MLPの訓練ループはソフトマックス回帰のものとまったく同じである。モデル、データ、トレーナーを定義し、最後にモデルとデータについてfitメソッドを呼び出す。
model = MLPScratch(num_inputs=784, num_outputs=10, num_hiddens=256, lr=0.1)
data = d2l.FashionMNIST(batch_size=256)
trainer = d2l.Trainer(max_epochs=10)
trainer.fit(model, data)