第6章構築者のための手引き
6.2.2. Tied Parameters6.2.2 結びつけられたパラメータ
Often, we want to share parameters across multiple layers. Let’s see how to do this elegantly. In the following we allocate a fully connected layer and then use its parameters specifically to set those of another layer. Here we need to run the forward propagation
net(X) before accessing the parameters.英語のヒント
複数の層のあいだでパラメータを共有したいことはよくある。これをすっきりと行う方法を見てみよう。以下では、全結合層を一つ割り当て、それからそのパラメータを使って、別の層のパラメータをそれに設定する。ここでは、パラメータにアクセスする前に、順伝播
net(X)を実行しておく必要がある。# We need to give the shared layer a name so that we can refer to its
# parameters
shared = nn.LazyLinear(8)
net = nn.Sequential(nn.LazyLinear(8), nn.ReLU(),
shared, nn.ReLU(),
shared, nn.ReLU(),
nn.LazyLinear(1))
net(X)
# Check whether the parameters are the same
print(net[2].weight.data[0] == net[4].weight.data[0])
net[2].weight.data[0, 0] = 100
# Make sure that they are actually the same object rather than just having the
# same value
print(net[2].weight.data[0] == net[4].weight.data[0])tensor([True, True, True, True, True, True, True, True])
tensor([True, True, True, True, True, True, True, True])This example shows that the parameters of the second and third layer are tied. They are not just equal, they are represented by the same exact tensor. Thus, if we change one of the parameters, the other one changes, too.
英語のヒント
この例は、2番目と3番目の層のパラメータが結びつけられていることを示している。それらは単に等しいのではなく、まったく同じテンソルで表されている。したがって、一方のパラメータを変えると、もう一方も変わる。
You might wonder, when parameters are tied what happens to the gradients? Since the model parameters contain gradients, the gradients of the second hidden layer and the third hidden layer are added together during backpropagation.
英語のヒント
パラメータが結びつけられているとき、勾配はどうなるのかと思うかもしれない。モデルのパラメータは勾配を含むので、逆伝播のあいだに、2番目の隠れ層と3番目の隠れ層の勾配は足し合わされる。