pytorch masked_fill:为什么我不能屏蔽所有零?

Yin*_*Gao 3 python tensorflow pytorch

我想用 屏蔽分数矩阵中的所有零-np.inf,但我只能屏蔽部分零,看起来像

在此处输入图片说明

你在右上角看到还有没有被掩盖的零 -np.inf

这是我的代码:

q = torch.Tensor([np.random.random(10),np.random.random(10),np.random.random(10), np.random.random(10), np.zeros((10,1)), np.zeros((10,1))])
k = torch.Tensor([np.random.random(10),np.random.random(10),np.random.random(10), np.random.random(10), np.zeros((10,1)), np.zeros((10,1))])
scores = torch.matmul(q, k.transpose(0,1)) / math.sqrt(10)
mask = torch.Tensor([1,1,1,1,0,0])
mask = mask.unsqueeze(1)
scores = scores.masked_fill(mask==0, -np.inf)
Run Code Online (Sandbox Code Playgroud)

也许面具是错的?

muj*_*iga 7

你的面具错了。尝试

scores = scores.masked_fill(scores == 0, -np.inf)
Run Code Online (Sandbox Code Playgroud)

scores 现在看起来像

tensor([[1.4796, 1.2361, 1.2137, 0.9487,   -inf,   -inf],
        [0.6889, 0.4428, 0.6302, 0.4388,   -inf,   -inf],
        [0.8842, 0.7614, 0.8311, 0.6431,   -inf,   -inf],
        [0.9884, 0.8430, 0.7982, 0.7323,   -inf,   -inf],
        [  -inf,   -inf,   -inf,   -inf,   -inf,   -inf],
        [  -inf,   -inf,   -inf,   -inf,   -inf,   -inf]])
Run Code Online (Sandbox Code Playgroud)