加速numpy kronecker产品

ste*_*ejb 7 python numpy

我正在研究我的第一个大型python项目.我有一个函数,其中包含以下代码:

            # EXPAND THE EXPECTED VALUE TO APPLY TO ALL STATES,
            # THEN UPDATE fullFnMat
            EV_subset_expand = np.kron(EV_subset, np.ones((nrows, 1)))
            fullFnMat[key] = staticMat[key] + EV_subset_expand                
Run Code Online (Sandbox Code Playgroud)

在我的代码分析器中,似乎这个kronecker产品实际上占用了大量的时间.

Function                                                                                        was called by...
                                                                                                    ncalls  tottime  cumtime
/home/stevejb/myhg/dpsolve/ootest/tests/ddw2011/profile_dir/BellmanEquation.py:17(bellmanFn)    <-      19   37.681   38.768  /home/stevejb/myhg/dpsolve/ootest/tests/ddw2011/profile_dir/dpclient.py:467(solveTheModel)
{numpy.core.multiarray.concatenate}                                                             <-     342   27.319   27.319  /usr/lib/pymodules/python2.7/numpy/lib/shape_base.py:665(kron)
/home/stevejb/myhg/dpsolve/ootest/tests/ddw2011/profile_dir/dpclient.py:467(solveTheModel)      <-       1   11.041   91.781  <string>:1(<module>)
{method 'argsort' of 'numpy.ndarray' objects}                                                   <-      19    7.692    7.692  /usr/lib/pymodules/python2.7/numpy/core/fromnumeric.py:597(argsort)
/usr/lib/pymodules/python2.7/numpy/core/numeric.py:789(outer)                                   <-     171    2.526    2.527  /usr/lib/pymodules/python2.7/numpy/lib/shape_base.py:665(kron)
{method 'max' of 'numpy.ndarray' objects}                                                       <-     209    2.034    2.034  /home/stevejb/myhg/dpsolve/ootest/tests/ddw2011/profile_dir/dpclient.py:391(getValPolMatrices)
Run Code Online (Sandbox Code Playgroud)

有没有办法在Numpy中获得更快的kronecker产品?它似乎不应该花费很长时间.

Jos*_*del 7

你当然可以看看源代码np.kron.它可以在中找到numpy/lib/shape_base.py,您可以看到是否有可以进行的改进或可以使其更有效的简化.或者,您可以使用Cython或其他一些低级语言绑定来编写自己的语言,以尝试获得更好的性能.

或者正如@matt建议的那样,以下内容可能本身更快:

import numpy as np
nrows = 10
a = np.arange(100).reshape(10,10)
b = np.tile(a,nrows).reshape(nrows*a.shape[0],-1) # equiv to np.kron(a,np.ones((nrows,1)))
Run Code Online (Sandbox Code Playgroud)

要么:

b = np.repeat(a,nrows*np.ones(a.shape[0],np.int),axis=0)
Run Code Online (Sandbox Code Playgroud)

时序:

In [80]: %timeit np.tile(a,nrows).reshape(nrows*a.shape[0],-1)
10000 loops, best of 3: 25.5 us per loop

In [81]: %timeit np.kron(a,np.ones((nrows,1)))
10000 loops, best of 3: 117 us per loop

In [91]: %timeit np.repeat(a,nrows*np.ones(a.shape[0],np.int),0)
100000 loops, best of 3: 12.8 us per loop
Run Code Online (Sandbox Code Playgroud)

np.repeat在上面的例子中使用大小的数组可以提供非常漂亮的10倍加速,这不是太糟糕.