如何将numpy数组幂运算?(对应重复矩阵乘法,而非逐元素)

22 投票
2 回答
53600 浏览
提问于 2025-04-16 11:56

我想把一个二维的numpy array,我们叫它A,提升到某个数字n的幂,但到目前为止我还没找到合适的函数或操作符来做到这一点。

我知道我可以把它转换成matrix类型,然后利用这个特性(就像在Matlab中的表现一样),A**n正好可以满足我的需求,(对于array来说,同样的表达式是逐元素的幂运算)。不过,把它转换成matrix再转换回来,感觉是个比较麻烦的解决办法。

肯定有更好的方法可以在保持array格式的情况下进行这个计算吧?

2 个回答

-1

在我的电脑上,opencv的cvPow函数在计算有理数的幂时,速度似乎快了3到4倍。下面是一个示例函数(你需要安装pyopencv模块):

import pyopencv as pycv
import numpy
def pycv_power(arr, exponent):
    """Raise the elements of a floating point matrix to a power. 
    It is 3-4 times faster than numpy's built-in power function/operator."""
    if arr.dtype not in [numpy.float32, numpy.float64]:
        arr = arr.astype('f')
    res = numpy.empty_like(arr)
    if arr.flags['C_CONTIGUOUS'] == False:
        arr = numpy.ascontiguousarray(arr)        
    pycv.pow(pycv.asMat(arr), float(exponent), pycv.asMat(res))
    return res   
35

我觉得你想要的是 numpy.linalg.matrix_power

这里有个简单的例子:

import numpy as np
x = np.arange(9).reshape(3,3)
y = np.matrix(x)

a = y**3
b = np.linalg.matrix_power(x, 3)

print a
print b
assert np.all(a==b)

这样会得到:

In [19]: a
Out[19]: 
matrix([[ 180,  234,  288],
        [ 558,  720,  882],
        [ 936, 1206, 1476]])

In [20]: b
Out[20]: 
array([[ 180,  234,  288],
       [ 558,  720,  882],
       [ 936, 1206, 1476]])

撰写回答