np.where() 在处理数组中的零元素除法时存在错误[重复]

问题描述 投票:0回答:0

当我想避免除法中遇到零的情况时,我用

np.where(a != 0, b / a, 0)
来判断,发现了一个RuntimeWarning: 除法中遇到零的情况。这是有线的,因为我在 pytorch 中使用张量执行相同的操作,所以没有出现警告。测试代码如下所示。谁能告诉我为什么 numpy 会发出这个警告但结果是正确的,而在 pytorch 中却工作得很好?

a = torch.tensor([[[4, 0,], [4, 4]], [[3, 3,], [3, 3]]])
b = np.ones((2, 2, 2))
# print(a.shape)
b = torch.where(a != 0, b / a, 0)
print(b)

a = np.array([[[4, 0,], [4, 4]], [[3, 3,], [3, 3]]])
b = np.ones((2, 2, 2))
# print(a.shape)
b = np.where(a != 0, b / a, 0)
print(b)

结果如下所示:

tensor([[[0.2500, 0.0000],
         [0.2500, 0.2500]],

        [[0.3333, 0.3333],
         [0.3333, 0.3333]]], dtype=torch.float64)
private/test.py:77: RuntimeWarning: divide by zero encountered in divide
  b = np.where(a != 0, b / a, 0)
[[[0.25       0.        ]
  [0.25       0.25      ]]

 [[0.33333333 0.33333333]
  [0.33333333 0.33333333]]]
numpy divide-by-zero
© www.soinside.com 2019 - 2024. All rights reserved.