第6章構築者のための手引き
6.5.1. Layers without Parameters6.5.1 パラメータのない層
To start, we construct a custom layer that does not have any parameters of its own. This should look familiar if you recall our introduction to modules in Section 6.1. The following
CenteredLayer class simply subtracts the mean from its input. To build it, we simply need to inherit from the base layer class and implement the forward propagation function.英語のヒント
まず、自分のパラメータをもたない独自の層を作る。6.1節でのモジュールの紹介を思い出せば、これは見覚えがあるはずである。次の
CenteredLayerクラスは、入力から平均を引くだけである。これを作るには、基底の層のクラスを継承し、順伝播の関数を実装するだけでよい。class CenteredLayer(nn.Module):
def __init__(self):
super().__init__()
def forward(self, X):
return X - X.mean()Let’s verify that our layer works as intended by feeding some data through it.
英語のヒント
データを通してみて、層が意図どおりに働くことを確かめよう。
layer = CenteredLayer()
layer(torch.tensor([1.0, 2, 3, 4, 5]))tensor([-2., -1., 0., 1., 2.])We can now incorporate our layer as a component in constructing more complex models.
英語のヒント
これで、この層を部品として組み込んで、もっと複雑なモデルを組み立てられる。
net = nn.Sequential(nn.LazyLinear(128), CenteredLayer())As an extra sanity check, we can send random data through the network and check that the mean is in fact 0. Because we are dealing with floating point numbers, we may still see a very small nonzero number due to quantization.
英語のヒント
念のための正常性の確認として、ネットワークに無作為なデータを通し、平均が実際に0であることを確かめられる。浮動小数点数を扱っているので、量子化のせいで、0でないごく小さな数が見えることもある。
Y = net(torch.rand(4, 8))
Y.mean()tensor(-6.5193e-09, grad_fn=<MeanBackward0>)