第5章多層パーセプトロン
5.2.2. Concise Implementation5.2.2 簡潔な実装
As you might expect, by relying on the high-level APIs, we can implement MLPs even more concisely.
英語のヒント
予想されるとおり、高水準のAPIに頼れば、MLPをさらに簡潔に実装できる。
5.2.2.1. Model5.2.2.1 モデル
Compared with our concise implementation of softmax regression implementation (Section 4.5), the only difference is that we add two fully connected layers where we previously added only one. The first is the hidden layer, the second is the output layer.
英語のヒント
ソフトマックス回帰の簡潔な実装(4.5節)と比べると、唯一の違いは、以前は全結合層を一つしか加えなかったところに、二つ加えることである。一つ目は隠れ層、二つ目は出力層である。
class MLP(d2l.Classifier):
def __init__(self, num_outputs, num_hiddens, lr):
super().__init__()
self.save_hyperparameters()
self.net = nn.Sequential(nn.Flatten(), nn.LazyLinear(num_hiddens),
nn.ReLU(), nn.LazyLinear(num_outputs))Previously, we defined
forward methods for models to transform input using the model parameters. These operations are essentially a pipeline: you take an input and apply a transformation (e.g., matrix multiplication with weights followed by bias addition), then repetitively use the output of the current transformation as input to the next transformation. However, you may have noticed that no forward method is defined here. In fact, MLP inherits the forward method from the Module class (Section 3.2.2) to simply invoke self.net(X) (X is input), which is now defined as a sequence of transformations via the Sequential class. The Sequential class abstracts the forward process enabling us to focus on the transformations. We will further discuss how the Sequential class works in Section 6.1.2.英語のヒント
以前は、モデルのパラメータを使って入力を変換するために、モデルに
forwardメソッドを定義した。こうした演算は、本質的にはパイプラインである。入力を受け取って変換(たとえば、重みとの行列の掛け算と、それに続くバイアスの足し算)を当てはめ、それから今の変換の出力を次の変換への入力として繰り返し使うのである。しかし、ここではforwardメソッドが定義されていないことに気づいたかもしれない。実は、MLPはModuleクラス(3.2.2節)からforwardメソッドを受け継いで、単にself.net(X)(Xは入力)を呼び出しており、それが今ではSequentialクラスによって変換の並びとして定義されている。Sequentialクラスは順伝播の過程を抽象化し、変換に集中できるようにしてくれる。Sequentialクラスがどう働くかは、6.1.2節でさらに論じる。5.2.2.2. Training5.2.2.2 訓練
The training loop is exactly the same as when we implemented softmax regression. This modularity enables us to separate matters concerning the model architecture from orthogonal considerations.
英語のヒント
訓練ループは、ソフトマックス回帰を実装したときとまったく同じである。このモジュール性のおかげで、モデルの構造にかかわる事柄を、それとは独立な検討事項から切り離せる。
model = MLP(num_outputs=10, num_hiddens=256, lr=0.1)
trainer.fit(model, data)