16 python optimization numpy cython scipy
我试图在Cython中进行计算,这很大程度上依赖于一些numpy/scipy数学函数numpy.log.我注意到如果我在Cython的循环中反复调用numpy/scipy函数,则会产生巨大的开销,例如:
import numpy as np
cimport numpy as np
np.import_array()
cimport cython
def myloop(int num_elts):
cdef double value = 0
for n in xrange(num_elts):
# call numpy function
value = np.log(2)
Run Code Online (Sandbox Code Playgroud)
这非常昂贵,大概是因为np.log通过Python而不是直接调用numpy C函数.如果我用以下内容替换该行:
from libc.math cimport log
...
# calling libc function 'log'
value = log(2)
Run Code Online (Sandbox Code Playgroud)
然后它会快得多.但是,当我尝试将numpy数组传递给libc.math.log时:
cdef np.ndarray[long, ndim=1] foo = np.array([1, 2, 3])
log(foo)
Run Code Online (Sandbox Code Playgroud)
它给出了这个错误:
TypeError: only length-1 arrays can be converted to Python scalars
Run Code Online (Sandbox Code Playgroud)
我的问题是:
foo上面的数组.)具体的例子:假设你想在Cython中循环中的scipy.stats.*标量值上调用许多scipy或numpy的有用统计函数(例如)for?在Cython中重新实现所有这些功能是很疯狂的,因此必须调用它们的C版本.例如,所有与pdf/cdf相关的函数和各种统计分布的抽样(例如参见http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.rv_continuous.pdf.html#scipy. stats.rv_continuous.pdf和http://www.johndcook.com/distributions_scipy.html)如果你在循环中用Python开销调用这些函数,它将会非常慢.
谢谢.
您无法在 numpy 数组上应用 log 等 C 函数,并且 numpy 没有可以从 cython 调用的 C 函数库。
Numpy 函数已经经过优化,可以在 numpy 数组上调用。除非您有非常独特的用例,否则您不会从将 numpy 函数重新实现为 C 函数中获得太多好处。(numpy 中的某些函数可能没有很好地实现,在这种情况下请考虑将您的输入作为补丁提交。)但是您确实提出了一个很好的观点。
# A
from libc.math cimport log
for i in range(N):
r[i] = log(foo[i])
# B
r = np.log(foo)
# C
for i in range(n):
r[i] = np.log(foo[i])
Run Code Online (Sandbox Code Playgroud)
一般来说,A 和 B 应该有相似的运行时间,但 C 应该避免,并且会慢很多。
更新
这是 scipy.stats.norm.pdf 的代码,您可以看到它是用 python 编写的,带有 numpy 和 scipy 调用。该代码没有 C 版本,您必须“通过 python”调用它。如果这是阻碍您的原因,您需要将其重新植入 C/Cython 中,但首先我会花一些时间非常仔细地分析代码,看看是否有任何容易实现的目标。
def pdf(self,x,*args,**kwds):
loc,scale=map(kwds.get,['loc','scale'])
args, loc, scale = self._fix_loc_scale(args, loc, scale)
x,loc,scale = map(asarray,(x,loc,scale))
args = tuple(map(asarray,args))
x = asarray((x-loc)*1.0/scale)
cond0 = self._argcheck(*args) & (scale > 0)
cond1 = (scale > 0) & (x >= self.a) & (x <= self.b)
cond = cond0 & cond1
output = zeros(shape(cond),'d')
putmask(output,(1-cond0)+np.isnan(x),self.badvalue)
if any(cond):
goodargs = argsreduce(cond, *((x,)+args+(scale,)))
scale, goodargs = goodargs[-1], goodargs[:-1]
place(output,cond,self._pdf(*goodargs) / scale)
if output.ndim == 0:
return output[()]
return output
Run Code Online (Sandbox Code Playgroud)