プリンキピア

第5章多層パーセプトロン

5.6.2. Implementation from Scratch5.6.2 ゼロからの実装

To implement the dropout function for a single layer, we must draw as many samples from a Bernoulli (binary) random variable as our layer has dimensions, where the random variable takes value 1 (keep) with probability 1−p and 0 (drop) with probability p. One easy way to implement this is to first draw samples from the uniform distribution U[0,1]. Then we can keep those nodes for which the corresponding sample is greater than p, dropping the rest.
英語のヒント
一つの層のためのドロップアウト関数を実装するには、層の次元の数と同じだけの標本を、ベルヌーイ(二値)確率変数から取り出さなければならない。この確率変数は、確率1−pで値1(残す)を、確率pで値0(落とす)をとる。これを実装する簡単な方法の一つは、まず一様分布U[0,1]から標本を取り出すことである。それから、対応する標本がpより大きいノードを残し、残りを落とせばよい。
In the following code, we implement a dropout_layer function that drops out the elements in the tensor input X with probability dropout, rescaling the remainder as described above: dividing the survivors by 1.0-dropout.
英語のヒント
次のコードでは、テンソルの入力Xの要素を確率dropoutで脱落させ、残りを上で説明したように、つまり生き残ったものを1.0-dropoutで割って、スケールし直すdropout_layer関数を実装する。
def dropout_layer(X, dropout):
    assert 0 <= dropout <= 1
    if dropout == 1: return torch.zeros_like(X)
    mask = (torch.rand(X.shape) > dropout).float()
    return mask * X / (1.0 - dropout)
We can test out the dropout_layer function on a few examples. In the following lines of code, we pass our input X through the dropout operation, with probabilities 0, 0.5, and 1, respectively.
英語のヒント
いくつかの例でdropout_layer関数を試してみよう。次の数行のコードでは、入力Xをドロップアウト演算に、確率をそれぞれ0、0.5、1にして通す。
X = torch.arange(16, dtype = torch.float32).reshape((2, 8))
print('dropout_p = 0:', dropout_layer(X, 0))
print('dropout_p = 0.5:', dropout_layer(X, 0.5))
print('dropout_p = 1:', dropout_layer(X, 1))
dropout_p = 0: tensor([[ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.],
        [ 8.,  9., 10., 11., 12., 13., 14., 15.]])
dropout_p = 0.5: tensor([[ 0.,  2.,  0.,  6.,  8.,  0.,  0.,  0.],
        [16., 18., 20., 22., 24., 26., 28., 30.]])
dropout_p = 1: tensor([[0., 0., 0., 0., 0., 0., 0., 0.],
        [0., 0., 0., 0., 0., 0., 0., 0.]])

5.6.2.1. Defining the Model5.6.2.1 モデルの定義

The model below applies dropout to the output of each hidden layer (following the activation function). We can set dropout probabilities for each layer separately. A common choice is to set a lower dropout probability closer to the input layer. We ensure that dropout is only active during training.
英語のヒント
下のモデルは、(活性化関数の後で)各隠れ層の出力にドロップアウトを当てはめる。ドロップアウトの確率は層ごとに別々に設定できる。よくある選び方は、入力層に近いほどドロップアウトの確率を低くすることである。ドロップアウトが訓練中にだけ働くようにする。
class DropoutMLPScratch(d2l.Classifier):
    def __init__(self, num_outputs, num_hiddens_1, num_hiddens_2,
                 dropout_1, dropout_2, lr):
        super().__init__()
        self.save_hyperparameters()
        self.lin1 = nn.LazyLinear(num_hiddens_1)
        self.lin2 = nn.LazyLinear(num_hiddens_2)
        self.lin3 = nn.LazyLinear(num_outputs)
        self.relu = nn.ReLU()

    def forward(self, X):
        H1 = self.relu(self.lin1(X.reshape((X.shape[0], -1))))
        if self.training:
            H1 = dropout_layer(H1, self.dropout_1)
        H2 = self.relu(self.lin2(H1))
        if self.training:
            H2 = dropout_layer(H2, self.dropout_2)
        return self.lin3(H2)

5.6.2.2. Training5.6.2.2 訓練

The following is similar to the training of MLPs described previously.
英語のヒント
以下は、前に説明したMLPの訓練と似ている。
hparams = {'num_outputs':10, 'num_hiddens_1':256, 'num_hiddens_2':256,
           'dropout_1':0.5, 'dropout_2':0.5, 'lr':0.1}
model = DropoutMLPScratch(**hparams)
data = d2l.FashionMNIST(batch_size=256)
trainer = d2l.Trainer(max_epochs=10)
trainer.fit(model, data)