注意力评分函数

为什么要除以根号d,而不是直接除以d呢?

人傻了,标准化的公式就是除以标准差,而d是方差,所以要开平方。属于是自问自答了。

1 Like
def masked_softmax(X, valid_lens):
    """通过在最后一个轴上掩蔽元素来执行softmax操作"""
    # X:3D张量,valid_lens:1D或2D张量
    if valid_lens is None:
        return nn.functional.softmax(X, dim=-1)
    else:
        shape = X.shape
        if valid_lens.dim() == 1:
            valid_lens = torch.repeat_interleave(valid_lens, shape[1])
        else:
            valid_lens = valid_lens.reshape(-1)
        # 最后一轴上被掩蔽的元素使用一个非常大的负值替换,从而其softmax输出为0
        X = d2l.sequence_mask(X.reshape(-1, shape[-1]), valid_lens,
                              value=-1e6)
        return nn.functional.softmax(X.reshape(shape), dim=-1)

valid_lens = torch.repeat_interleave(valid_lens, shape[1])这一行的shape[1]应该改成shape[0]

我理解错了,就应该复制shape[1]次