第6章構築者のための手引き
6.1.1. A Custom Module6.1.1 独自のモジュール
Perhaps the easiest way to develop intuition about how a module works is to implement one ourselves. Before we do that, we briefly summarize the basic functionality that each module must provide:
英語のヒント
モジュールがどう働くかについて直観を養うおそらく最も簡単な方法は、自分で一つ実装してみることである。その前に、各モジュールが提供しなければならない基本的な機能を手短にまとめておく。
- Ingest input data as arguments to its forward propagation method.
英語のヒント
入力データを、順伝播のメソッドへの引数として取り込む。 - Generate an output by having the forward propagation method return a value. Note that the output may have a different shape from the input. For example, the first fully connected layer in our model above ingests an input of arbitrary dimension but returns an output of dimension 256.
英語のヒント
順伝播のメソッドに値を返させることで、出力を生成する。出力は入力と異なる形状をもちうることに注意してほしい。たとえば、上のモデルの最初の全結合層は、任意の次元の入力を取り込むが、次元256の出力を返す。 - Calculate the gradient of its output with respect to its input, which can be accessed via its backpropagation method. Typically this happens automatically.
英語のヒント
入力についての出力の勾配を計算する。これは逆伝播のメソッドを通じてアクセスできる。ふつう、これは自動で行われる。 - Store and provide access to those parameters necessary for executing the forward propagation computation.
英語のヒント
順伝播の計算を実行するのに必要なパラメータを保存し、それへのアクセスを提供する。 - Initialize model parameters as needed.
英語のヒント
必要に応じてモデルのパラメータを初期化する。
In the following snippet, we code up a module from scratch corresponding to an MLP with one hidden layer with 256 hidden units, and a 10-dimensional output layer. Note that the
MLP class below inherits the class that represents a module. We will heavily rely on the parent class’s methods, supplying only our own constructor (the __init__ method in Python) and the forward propagation method.英語のヒント
次のコード片では、256個の隠れユニットをもつ隠れ層が一つと、10次元の出力層をもつMLPに対応するモジュールを、ゼロから書き上げる。下の
MLPクラスは、モジュールを表すクラスを継承していることに注意してほしい。親クラスのメソッドに大きく頼り、自分のコンストラクタ(Pythonでは__init__メソッド)と順伝播のメソッドだけを用意する。class MLP(nn.Module):
def __init__(self):
# Call the constructor of the parent class nn.Module to perform
# the necessary initialization
super().__init__()
self.hidden = nn.LazyLinear(256)
self.out = nn.LazyLinear(10)
# Define the forward propagation of the model, that is, how to return the
# required model output based on the input X
def forward(self, X):
return self.out(F.relu(self.hidden(X)))Let’s first focus on the forward propagation method. Note that it takes
X as input, calculates the hidden representation with the activation function applied, and outputs its logits. In this MLP implementation, both layers are instance variables. To see why this is reasonable, imagine instantiating two MLPs, net1 and net2, and training them on different data. Naturally, we would expect them to represent two different learned models.英語のヒント
まず順伝播のメソッドに注目しよう。それは
Xを入力として受け取り、活性化関数を当てはめた隠れ表現を計算し、ロジットを出力することに注意してほしい。このMLPの実装では、両方の層がインスタンス変数である。これがなぜ理にかなっているかを見るため、二つのMLP、net1とnet2をインスタンス化し、異なるデータで訓練することを想像してほしい。当然、それらは異なる二つの学習済みモデルを表すと期待するだろう。We instantiate the MLP’s layers in the constructor and subsequently invoke these layers on each call to the forward propagation method. Note a few key details. First, our customized
__init__ method invokes the parent class’s __init__ method via super().__init__() sparing us the pain of restating boilerplate code applicable to most modules. We then instantiate our two fully connected layers, assigning them to self.hidden and self.out. Note that unless we implement a new layer, we need not worry about the backpropagation method or parameter initialization. The system will generate these methods automatically. Let’s try this out.英語のヒント
MLPの層はコンストラクタでインスタンス化し、その後、順伝播のメソッドを呼ぶたびにそれらの層を呼び出す。いくつかの鍵となる細部に注意してほしい。第一に、独自の
__init__メソッドは、super().__init__()を通じて親クラスの__init__メソッドを呼び出し、ほとんどのモジュールに当てはまる決まり文句のコードを書き直す手間を省いてくれる。それから二つの全結合層をインスタンス化し、それらをself.hiddenとself.outに割り当てる。新しい層を実装するのでないかぎり、逆伝播のメソッドやパラメータの初期化を気にする必要はないことに注意してほしい。システムがこれらのメソッドを自動で生成してくれる。試してみよう。net = MLP()
net(X).shapetorch.Size([2, 10])A key virtue of the module abstraction is its versatility. We can subclass a module to create layers (such as the fully connected layer class), entire models (such as the
MLP class above), or various components of intermediate complexity. We exploit this versatility throughout the coming chapters, such as when addressing convolutional neural networks.英語のヒント
モジュールという抽象化の鍵となる長所は、その汎用性である。モジュールをサブクラス化して、層(全結合層のクラスなど)、モデル全体(上の
MLPクラスなど)、あるいは中くらいの複雑さのさまざまな部品を作れる。この汎用性は、畳み込みニューラルネットワークを扱うときなど、以降の章を通じて活用する。