脾气暴躁的“哪里"函数不能避免评估Sqrt(负) [英] Numpy "Where" function can not avoid evaluate Sqrt(negative)
问题描述
np.where
函数似乎先评估所有可能的结果,然后再评估条件.这意味着,就我而言,即使以后不再使用,它也会求出-5,-4,-3,-2,-1的平方根.
It seems that the np.where
function evaluates all the possible outcomes first, then it evaluates the condition later. This means that, in my case, it will evaluate square root of -5, -4, -3, -2, -1 even though it will not be used later on.
我的代码运行并运行.但是我的问题是警告.我避免使用循环来评估每个元素,因为它的运行速度比np.where
慢得多.
My code runs and works. But my problem is the warning. I avoided using a loop to evaluate each element, because it will run much slower than np.where
.
所以,我在这里问
- 有什么办法让
np.where
首先评估条件? - 我可以仅关闭此特定警告吗?怎么样?
- 如果有更好的建议,另一种更好的方法.
- Is there any way to make
np.where
evaluate the condition first? - Can I turn off just this specific warning? How?
- Another better way to do it if you have a better suggestion.
这里有一个简短的示例代码,与我的真实代码相对应,这是巨大的.但是本质上有同样的问题.
Here just a short example code corresponding my real code which is gigantic. But essentially has the same problem.
输入:
import numpy as np
c=np.arange(10)-5
d=np.where(c>=0, np.sqrt(c) ,c )
输出:
RuntimeWarning: invalid value encountered in sqrt
d=np.where(c>=0,np.sqrt(c),c)
推荐答案
有一种很多更好的方法.让我们看看您的代码在做什么,看看为什么.
There is a much better way of doing this. Let's take a look at what your code is doing to see why.
np.where
接受三个数组作为输入.数组不支持惰性求值.
np.where
accepts three arrays as inputs. Arrays do not support lazy evaluation.
d = np.where(c >= 0, np.sqrt(c), c)
因此,此行等效于
a = (c >= 0)
b = np.sqrt(c)
d = np.where(a, b, c)
请注意,在调用where
之前,将立即计算输入.
Notice that the inputs are computed immediately, before where
ever gets called.
幸运的是,您根本不需要使用where
.相反,只需使用布尔掩码:
Luckily, you don't need to use where
at all. Instead, just use a boolean mask:
mask = (c >= 0)
d = np.empty_like(c)
d[mask] = np.sqrt(c[mask])
d[~mask] = c[~mask]
如果您期望有很多负面因素,则可以复制所有元素,而不仅仅是负面元素:
If you expect a lot of negatives, you can copy all the elements instead of just the negative ones:
d = c.copy()
d[mask] = np.sqrt(c[mask])
一个更好的解决方案可能是使用掩码数组:
An even better solution might be to use masked arrays:
d = np.ma(c, c < 0)
d = np.ma.sqrt(d)
要访问整个数据数组,且未更改被遮罩的部分,请使用d.data
.
To access the whole data array, with the masked portion unaltered, use d.data
.
这篇关于脾气暴躁的“哪里"函数不能避免评估Sqrt(负)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!