【发布时间】:2017-08-07 14:08:57
【问题描述】:
我发现我的模拟中的瓶颈之一是从泊松分布生成随机数。我的原始代码是这样工作的
import numpy as np
#Generating some data. In the actual code this comes from the previous
#steps in the simulation. But this gives an example of the type of data
n = 5000000
pop_n = np.array([range(500000)])
pop_n[:] = np.random.poisson(lam=n*pop_n/np.sum(pop_n))
现在,我读到 numba 可以非常简单地提高速度。我定义了函数
from numba import jit
@jit()
def poisson(n, pop_n, np=np):
return np.random.poisson(lam=n*pop_n/np.sum(pop_n))
这个确实比原来的跑得快。但是,我尝试更进一步:) 当我写的时候
@jit(nopython=True)
def poisson(n, pop_n, np=np):
return np.random.poisson(lam=n*pop_n/np.sum(pop_n))
我明白了
Failed at nopython (nopython frontend)
Invalid usage of Function(np.random.poisson) with parameters (array(float64, 1d, C))
Known signatures:
* (float64,) -> int64
* () -> int64
* parameterized
一些问题为什么会发生此错误以及如何修复它。
有更好的优化吗?
【问题讨论】:
-
看起来 Numba 还不支持从任何 np.random 函数返回数组。您应该首先设置一个空数组,指定其项目的类型,并且只有在您可以添加值之后。在此处查看示例github.com/numba/numba/issues/1596
-
我看不出任何实际的理由来说明为什么 jitting 这个函数应该更快。
np.random.poisson已经在 C 中实现。将其包装在另一个编译函数中最多会被编译器优化掉,最坏的情况是会导致开销。 -
@kazemakase pop_n 上的操作呢?数组除以它的总和?
-
@DiogoSantos 与生成随机数相比,这些操作可能可以忽略不计。我
%timeited 你的poisson函数有和没有@jit并没有看到任何改进。
标签: python python-2.7 numpy random numba