第6章構築者のための手引き
6.5.2. Layers with Parameters6.5.2 パラメータのある層
Now that we know how to define simple layers, let’s move on to defining layers with parameters that can be adjusted through training. We can use built-in functions to create parameters, which provide some basic housekeeping functionality. In particular, they govern access, initialization, sharing, saving, and loading model parameters. This way, among other benefits, we will not need to write custom serialization routines for every custom layer.
英語のヒント
単純な層を定義する方法がわかったので、訓練を通じて調整できるパラメータをもつ層の定義に進もう。組み込みの関数を使ってパラメータを作れば、基本的な雑務の機能をいくつか用意してくれる。特に、モデルのパラメータへのアクセス、初期化、共有、保存、読み込みを取り仕切ってくれる。こうすれば、ほかの利点もあるが、独自の層ごとに独自の直列化の処理を書く必要がなくなる。
Now let’s implement our own version of the fully connected layer. Recall that this layer requires two parameters, one to represent the weight and the other for the bias. In this implementation, we bake in the ReLU activation as a default. This layer requires two input arguments:
in_units and units, which denote the number of inputs and outputs, respectively.英語のヒント
では、全結合層の自分なりの版を実装しよう。この層には、重みを表すものとバイアスを表すものの、二つのパラメータが必要であることを思い出してほしい。この実装では、既定でReLU活性化を組み込んでおく。この層には、それぞれ入力と出力の数を表す、
in_unitsとunitsの二つの入力引数が必要である。class MyLinear(nn.Module):
def __init__(self, in_units, units):
super().__init__()
self.weight = nn.Parameter(torch.randn(in_units, units))
self.bias = nn.Parameter(torch.randn(units,))
def forward(self, X):
linear = torch.matmul(X, self.weight.data) + self.bias.data
return F.relu(linear)Next, we instantiate the
MyLinear class and access its model parameters.英語のヒント
次に、
MyLinearクラスをインスタンス化し、そのモデルのパラメータにアクセスする。linear = MyLinear(5, 3)
linear.weightParameter containing:
tensor([[ 0.4783, 0.4284, -0.0899],
[-0.6347, 0.2913, -0.0822],
[-0.4325, -0.1645, -0.3274],
[ 1.1898, 0.6482, -1.2384],
[-0.1479, 0.0264, -0.9597]], requires_grad=True)We can directly carry out forward propagation calculations using custom layers.
英語のヒント
独自の層を使って、順伝播の計算を直接行える。
linear(torch.rand(2, 5))tensor([[0.0000, 0.9316, 0.0000],
[0.1808, 1.4208, 0.0000]])We can also construct models using custom layers. Once we have that we can use it just like the built-in fully connected layer.
英語のヒント
独自の層を使ってモデルを組み立てることもできる。そうすれば、それを組み込みの全結合層とまったく同じように使える。
net = nn.Sequential(MyLinear(64, 8), MyLinear(8, 1))
net(torch.rand(2, 64))tensor([[ 0.0000],
[13.0800]])