第6章構築者のための手引き
6.2.1. Parameter Access6.2.1 パラメータへのアクセス
Let’s start with how to access parameters from the models that you already know.
英語のヒント
すでに知っているモデルから、パラメータにどうアクセスするかから始めよう。
When a model is defined via the
Sequential class, we can first access any layer by indexing into the model as though it were a list. Each layer’s parameters are conveniently located in its attribute.英語のヒント
モデルが
Sequentialクラスで定義されているときは、まるでリストであるかのようにモデルに添え字を付けて、どの層にもアクセスできる。各層のパラメータは、都合よくその属性に収められている。We can inspect the parameters of the second fully connected layer as follows.
英語のヒント
2番目の全結合層のパラメータは、次のように調べられる。
net[2].state_dict()OrderedDict([('weight',
tensor([[-0.1649, 0.0605, 0.1694, -0.2524, 0.3526, -0.3414, -0.2322, 0.0822]])),
('bias', tensor([0.0709]))])We can see that this fully connected layer contains two parameters, corresponding to that layer’s weights and biases, respectively.
英語のヒント
この全結合層には、それぞれその層の重みとバイアスに対応する二つのパラメータが含まれていることがわかる。
6.2.1.1. Targeted Parameters6.2.1.1 特定のパラメータ
Note that each parameter is represented as an instance of the parameter class. To do anything useful with the parameters, we first need to access the underlying numerical values. There are several ways to do this. Some are simpler while others are more general. The following code extracts the bias from the second neural network layer, which returns a parameter class instance, and further accesses that parameter’s value.
英語のヒント
各パラメータは、パラメータクラスのインスタンスとして表されることに注意してほしい。パラメータで何か役に立つことをするには、まずその中にある数値にアクセスする必要がある。その方法はいくつかある。もっと単純なものもあれば、もっと汎用的なものもある。次のコードは、ニューラルネットワークの2番目の層からバイアスを取り出し(これはパラメータクラスのインスタンスを返す)、さらにそのパラメータの値にアクセスする。
type(net[2].bias), net[2].bias.data(torch.nn.parameter.Parameter, tensor([0.0709]))Parameters are complex objects, containing values, gradients, and additional information. That is why we need to request the value explicitly.
英語のヒント
パラメータは、値、勾配、追加の情報を含む複雑なオブジェクトである。だからこそ、値を明示的に要求する必要がある。
In addition to the value, each parameter also allows us to access the gradient. Because we have not invoked backpropagation for this network yet, it is in its initial state.
英語のヒント
値に加えて、各パラメータでは勾配にもアクセスできる。このネットワークではまだ逆伝播を呼び出していないので、勾配は初期状態にある。
net[2].weight.grad == NoneTrue6.2.1.2. All Parameters at Once6.2.1.2 すべてのパラメータを一度に
When we need to perform operations on all parameters, accessing them one-by-one can grow tedious. The situation can grow especially unwieldy when we work with more complex, e.g., nested, modules, since we would need to recurse through the entire tree to extract each sub-module’s parameters. Below we demonstrate accessing the parameters of all layers.
英語のヒント
すべてのパラメータに演算を行う必要があるとき、一つずつアクセスするのはうんざりする作業になりうる。もっと複雑な、たとえば入れ子になったモジュールを扱うときには、各サブモジュールのパラメータを取り出すのに木全体を再帰的にたどる必要があるので、事態は特に手に負えなくなりうる。下では、すべての層のパラメータにアクセスしてみせる。
[(name, param.shape) for name, param in net.named_parameters()][('0.weight', torch.Size([8, 4])),
('0.bias', torch.Size([8])),
('2.weight', torch.Size([1, 8])),
('2.bias', torch.Size([1]))]