RuntimeWarning:除以零错误:如何避免?PYTHON,NUMPY

pg2*_*455 5 python numpy

我正在运行RuntimeWarning:在divide中遇到无效值

 import numpy
 a = numpy.random.rand((1000000, 100))
 b = numpy.random.rand((1,100))
 dots = numpy.dot(b,a.T)/numpy.dot(b,b)
 norms = numpy.linalg.norm(a, axis =1)
 angles = dots/norms ### Basically I am calculating angle between 2 vectors 
Run Code Online (Sandbox Code Playgroud)

我的a中有一些向量的范数为0.因此在计算角度时它会给出运行时警告.

是否有一线pythonic方法来计算角度,同时考虑到0的规范?

angles =[i/j if j!=0 else -2 for i,j in zip(dots, norms)] # takes 10.6 seconds
Run Code Online (Sandbox Code Playgroud)

但这需要很多时间.由于所有角度的值都在1到-1之间,我只需要10个最大值,这对我有帮助.这需要大约10.6秒,这是疯了.

jta*_*lor 8

你可以忽略与np.errstate上下文管理器的warings,然后用你想要的东西替换nans :

import numpy as np
angle = np.arange(-5., 5.) 
norm = np.arange(10.)
with np.errstate(divide='ignore'):
    print np.where(norm != 0., angle / norm, -2)
# or:
with np.errstate(divide='ignore'):
    res = angle/norm
res[np.isnan(res)] = -2
Run Code Online (Sandbox Code Playgroud)


DSt*_*man 5

在较新版本的 numpy 中,还有第三种替代选项,可以避免使用 errstate 上下文管理器。

所有 Numpy ufunc都接受可选的“where”参数。这与 np.where 函数略有不同,因为它仅评估掩码为真的“其中”的函数。当掩码为 False 时,它​​不会更改值,因此使用“out”参数允许我们预先分配我们想要的任何默认值。

import numpy as np

angle = np.arange(-5., 5.)
norm = np.arange(10.)

# version 1
with np.errstate(divide='ignore'):
    res1 = np.where(norm != 0., angle / norm, -2)

# version 2
with np.errstate(divide='ignore'):
    res2 = angle/norm
res2[np.isinf(res2)] = -2

# version 3
res3 = -2. * np.ones(angle.shape)
np.divide(angle, norm, out=res3, where=norm != 0)

print(res1)
print(res2)
print(res3)

np.testing.assert_array_almost_equal(res1, res2)
np.testing.assert_array_almost_equal(res1, res3)
Run Code Online (Sandbox Code Playgroud)