プリンキピア

第10章現代のリカレントニューラルネットワーク

10.7.5. Loss Function with Masking10.7.5 マスクつきの損失関数

At each time step, the decoder predicts a probability distribution for the output tokens. As with language modeling, we can apply softmax to obtain the distribution and calculate the cross-entropy loss for optimization. Recall from Section 10.5 that the special padding tokens are appended to the end of sequences and so sequences of varying lengths can be efficiently loaded in minibatches of the same shape. However, prediction of padding tokens should be excluded from loss calculations. To this end, we can mask irrelevant entries with zero values so that multiplication of any irrelevant prediction with zero equates to zero.
英語のヒント
各時間ステップで、デコーダは出力トークンの確率分布を予測する。言語のモデリングと同じように、ソフトマックスを当てはめて分布を得て、最適化のために交差エントロピー損失を計算できる。10.5節で、特別な詰め物のトークンが系列の末尾に付け加えられ、そのため長さの異なる系列を同じ形状のミニバッチに効率よく読み込めることを思い出そう。しかし、詰め物のトークンの予測は損失の計算から除くべきである。そのために、関係のない要素を0の値でマスクし、関係のないどの予測も0を掛けると0になるようにできる。
@d2l.add_to_class(Seq2Seq)
def loss(self, Y_hat, Y):
    l = super(Seq2Seq, self).loss(Y_hat, Y, averaged=False)
    mask = (Y.reshape(-1) != self.tgt_pad).type(torch.float32)
    return (l * mask).sum() / mask.sum()