RuntimeWarning:除以零错误:如何避免? PYTHON,NUMPY [英] RuntimeWarning: Divide by Zero error: How to avoid? PYTHON, NUMPY
问题描述
我正在运行RuntimeWarning:除法中遇到无效的值
I am running in to RuntimeWarning: Invalid value encountered in 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.因此在计算角度时会发出运行时警告.
There are some vectors in my a which have norm as 0. so while calculating angles it is giving runtime warning.
在考虑0范数的情况下,是否存在一种单线pythonic方法来计算角度?
Is there a one line pythonic way to compute angles while taking into account norms which are 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秒,这太疯狂了.
But it takes a lot of time. Since all angles will have values between 1 and -1 and I need only 10 max values this will help me. This takes around 10.6 seconds which is insane.
推荐答案
您可以使用np.errstate
上下文管理器忽略警告,然后将nans替换为您想要的内容:
you can ignore warings with the np.errstate
context manager and later replace nans with what you want:
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
这篇关于RuntimeWarning:除以零错误:如何避免? PYTHON,NUMPY的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!