自定义numpy的向量化操作的效率问题 [英] Efficiency problem of customizing numpy's vectorized operation
问题描述
我有一个下面给出的python函数:
I have a python function given below:
def myfun(x):
if x > 0:
return 0
else:
return np.exp(x)
其中 np
是 numpy
库.我想让函数在 numpy 中向量化,所以我使用:
where np
is the numpy
library. I want to make the function vectorized in numpy, so I use:
vec_myfun = np.vectorize(myfun)
我做了一个测试来评估效率.首先我生成一个包含 100 个随机数的向量:
I did a test to evaluate the efficiency. First I generate a vector of 100 random numbers:
x = np.random.randn(100)
然后我运行以下代码来获取运行时:
Then I run the following code to obtain the runtime:
%timeit np.exp(x)
%timeit vec_myfun(x)
np.exp(x)
的运行时间为 1.07 µs ± 24.9 ns 每个循环(平均值 ± 标准偏差,7 次运行,每次 1000000 次循环)
.
vec_myfun(x)
的运行时间为 71.2 µs ± 1.68 µs 每个循环(平均值 ± 标准偏差,7 次运行,每次 10000 次循环)
我的问题是:与np.exp
相比,vec_myfun
只有一个额外的步骤来检查$x$的值,但它的运行速度比np.exp
.有没有一种有效的方法可以将 myfun
向量化,使其与 np.exp
一样高效?
My question is: compared to np.exp
, vec_myfun
has only one extra step to check the value of $x$, but it runs much slowly than np.exp
. Is there an efficient way to vectorize myfun
to make it as efficient as np.exp
?
推荐答案
ufunc
就像 np.exp
有一个 where
参数,它可以用作:
ufunc
like np.exp
have a where
parameter, which can be used as:
In [288]: x = np.random.randn(10)
In [289]: out=np.zeros_like(x)
In [290]: np.exp(x, out=out, where=(x<=0))
Out[290]:
array([0. , 0. , 0. , 0. , 0.09407685,
0.92458328, 0. , 0. , 0.46618914, 0. ])
In [291]: x
Out[291]:
array([ 0.37513573, 1.75273458, 0.30561659, 0.46554985, -2.3636433 ,
-0.07841215, 2.00878429, 0.58441085, -0.76316384, 0.12431333])
这实际上跳过了 where
为假的计算.
This actually skips the calculation where the where
is false.
相反:
np.where(arr > 0, 0, np.exp(arr))
首先为所有arr
计算np.exp(arr)
(这是正常的Python求值顺序),然后执行where
选择.使用这个 exp
没什么大不了的,但是使用 log
可能会有问题.
calculates np.exp(arr)
first for all arr
(that's normal Python evaluation order), and then performs the where
selection. With this exp
that isn't a big deal, but with log
it could be problems.
这篇关于自定义numpy的向量化操作的效率问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!