プリンキピア

第6章構築者のための手引き

6.3.1. Built-in Initialization6.3.1 組み込みの初期化

Let’s begin by calling on built-in initializers. The code below initializes all weight parameters as Gaussian random variables with standard deviation 0.01, while bias parameters are cleared to zero.
英語のヒント
まず、組み込みの初期化器を呼び出してみよう。下のコードは、重みパラメータをすべて標準偏差0.01のガウス分布の確率変数として初期化し、バイアスパラメータは0にする。
def init_normal(module):
    if type(module) == nn.Linear:
        nn.init.normal_(module.weight, mean=0, std=0.01)
        nn.init.zeros_(module.bias)

net.apply(init_normal)
net[0].weight.data[0], net[0].bias.data[0]
(tensor([-0.0129, -0.0007, -0.0033,  0.0276]), tensor(0.))
We can also initialize all the parameters to a given constant value (say, 1).
英語のヒント
すべてのパラメータを、与えられた定数(たとえば1)に初期化することもできる。
def init_constant(module):
    if type(module) == nn.Linear:
        nn.init.constant_(module.weight, 1)
        nn.init.zeros_(module.bias)

net.apply(init_constant)
net[0].weight.data[0], net[0].bias.data[0]
(tensor([1., 1., 1., 1.]), tensor(0.))
We can also apply different initializers for certain blocks. For example, below we initialize the first layer with the Xavier initializer and initialize the second layer to a constant value of 42.
英語のヒント
特定のブロックに異なる初期化器を当てはめることもできる。たとえば下では、最初の層をXavierの初期化器で初期化し、2番目の層を定数42に初期化する。
def init_xavier(module):
    if type(module) == nn.Linear:
        nn.init.xavier_uniform_(module.weight)

def init_42(module):
    if type(module) == nn.Linear:
        nn.init.constant_(module.weight, 42)

net[0].apply(init_xavier)
net[2].apply(init_42)
print(net[0].weight.data[0])
print(net[2].weight.data)
tensor([-0.0974,  0.1707,  0.5840, -0.5032])
tensor([[42., 42., 42., 42., 42., 42., 42., 42.]])

6.3.1.1. Custom Initialization6.3.1.1 独自の初期化

Sometimes, the initialization methods we need are not provided by the deep learning framework. In the example below, we define an initializer for any weight parameter w using the following strange distribution:
英語のヒント
必要な初期化の方法が、深層学習のフレームワークに用意されていないこともある。下の例では、次の奇妙な分布を使って、任意の重みパラメータwのための初期化器を定義する。
w∼{U(5,10) with probability 140 with probability 12U(−10,−5) with probability 14(6.3.1)
Again, we implement a my_init function to apply to net.
英語のヒント
ここでも、netに当てはめるmy_init関数を実装する。
def my_init(module):
    if type(module) == nn.Linear:
        print("Init", *[(name, param.shape)
                        for name, param in module.named_parameters()][0])
        nn.init.uniform_(module.weight, -10, 10)
        module.weight.data *= module.weight.data.abs() >= 5

net.apply(my_init)
net[0].weight[:2]
Init weight torch.Size([8, 4])
Init weight torch.Size([1, 8])
tensor([[ 0.0000, -7.6364, -0.0000, -6.1206],
        [ 9.3516, -0.0000,  5.1208, -8.4003]], grad_fn=<SliceBackward0>)
Note that we always have the option of setting parameters directly.
英語のヒント
パラメータを直接設定するという選択肢がいつもあることに注意してほしい。
net[0].weight.data[:] += 1
net[0].weight.data[0, 0] = 42
net[0].weight.data[0]
tensor([42.0000, -6.6364,  1.0000, -5.1206])