运行时警告:除以零错误:如何避免?Python,努比

2024-04-25 23:37:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在运行到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 

在我的a中有一些向量的范数是0。所以在计算角度时,它会给出运行时警告。

有没有一种计算角度的单线Python方法,同时考虑0的规范?

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

但这需要很多时间。因为所有角度的值都在1到-1之间,我只需要10个最大值,这对我有帮助。这大约需要10.6秒,这太疯狂了。


Tags: importnumpynormrandomdot角度anglesdots
3条回答

可以使用angles[~np.isfinite(angles)] = ...nan值替换为其他值。

例如:

In [103]: angles = dots/norms

In [104]: angles
Out[104]: array([[ nan,  nan,  nan, ...,  nan,  nan,  nan]])

In [105]: angles[~np.isfinite(angles)] = -2

In [106]: angles
Out[106]: array([[-2., -2., -2., ..., -2., -2., -2.]])

注意,除以零可能导致infs,而不是nans

In [140]: np.array([1, 2, 3, 4, 0])/np.array([1, 2, 0, -0., 0])
Out[140]: array([  1.,   1.,  inf, -inf,  nan])

因此,最好调用np.isfinite,而不是np.isnan来标识被零除的位置。

In [141]: np.isfinite(np.array([1, 2, 3, 4, 0])/np.array([1, 2, 0, -0., 0]))
Out[141]: array([ True,  True, False, False, False], dtype=bool)

注意,如果只需要NumPy数组的前十个值,那么使用np.argpartition函数可能比对整个数组进行完全排序要快,特别是对于大型数组:

In [110]: N = 3

In [111]: x = np.array([50, 40, 30, 20, 10, 0, 100, 90, 80, 70, 60])

In [112]: idx = np.argpartition(-x, N)

In [113]: idx
Out[113]: array([ 6,  7,  8,  9, 10,  0,  1,  4,  3,  2,  5])

In [114]: x[idx[:N]]
Out[114]: array([100,  90,  80])

这表明即使对于中等大小的数组,np.argpartition也更快:

In [123]: x = np.array([50, 40, 30, 20, 10, 0, 100, 90, 80, 70, 60]*1000)

In [124]: %timeit np.sort(x)[-N:]
1000 loops, best of 3: 233 µs per loop

In [125]: %timeit idx = np.argpartition(-x, N); x[idx[:N]]
10000 loops, best of 3: 53.3 µs per loop

你想使用np.where。请参阅documentation

angles = np.where(norms != 0, dots/norms, -2)

角度由downs/norms组成,否则为-2。您仍然会得到运行时警告,因为np.where仍将在内部计算整个向量dots/norms,但您可以安全地忽略它。

您可以使用np.errstate上下文管理器忽略警告,然后用所需内容替换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

相关问题 更多 >

    热门问题