第6章構築者のための手引き
6.1.2. The Sequential Module6.1.2 Sequentialモジュール
We can now take a closer look at how the
Sequential class works. Recall that Sequential was designed to daisy-chain other modules together. To build our own simplified MySequential, we just need to define two key methods:英語のヒント
これで、
Sequentialクラスがどう働くかを詳しく見られる。Sequentialは、ほかのモジュールを数珠つなぎにするために設計されたことを思い出してほしい。自分で簡略化したMySequentialを作るには、鍵となる二つのメソッドを定義するだけでよい。- A method for appending modules one by one to a list.
英語のヒント
モジュールを一つずつリストに追加していくメソッド。 - A forward propagation method for passing an input through the chain of modules, in the same order as they were appended.
英語のヒント
モジュールの鎖に、追加されたのと同じ順で入力を通していく順伝播のメソッド。
The following
MySequential class delivers the same functionality of the default Sequential class.英語のヒント
次の
MySequentialクラスは、既定のSequentialクラスと同じ機能を提供する。class MySequential(nn.Module):
def __init__(self, *args):
super().__init__()
for idx, module in enumerate(args):
self.add_module(str(idx), module)
def forward(self, X):
for module in self.children():
X = module(X)
return XIn the
__init__ method, we add every module by calling the add_modules method. These modules can be accessed by the children method at a later date. In this way the system knows the added modules, and it will properly initialize each module’s parameters.英語のヒント
__init__メソッドでは、add_modulesメソッドを呼んで、すべてのモジュールを加える。これらのモジュールには、後でchildrenメソッドでアクセスできる。こうして、システムは加えられたモジュールを把握し、各モジュールのパラメータを適切に初期化する。When our
MySequential’s forward propagation method is invoked, each added module is executed in the order in which they were added. We can now reimplement an MLP using our MySequential class.英語のヒント
MySequentialの順伝播のメソッドが呼び出されると、加えられた各モジュールは、加えられた順に実行される。これで、MySequentialクラスを使ってMLPを実装し直せる。net = MySequential(nn.LazyLinear(256), nn.ReLU(), nn.LazyLinear(10))
net(X).shapetorch.Size([2, 10])Note that this use of
MySequential is identical to the code we previously wrote for the Sequential class (as described in Section 5.1).英語のヒント
この
MySequentialの使い方は、(5.1節で説明したように)以前にSequentialクラスのために書いたコードと同じであることに注意してほしい。