Matrix power for sparse matrix in python

北城以北 提交于 2019-11-28 14:18:17

** has been implemented for csr_matrix. There is a __pow__ method.

After handling some special cases this __pow__ does:

            tmp = self.__pow__(other//2)
            if (other % 2):
                return self * tmp * tmp
            else:
                return tmp * tmp

For sparse matrix, * is the matrix product (dot for ndarray). So it is doing recursive multiplications.


As math noted, np.matrix also implements ** (__pow__) as matrix power. In fact it ends up calling np.linalg.matrix_power.

np.linalg.matrix_power(M, n) is written in Python, so you can easily see what it does.

For n<=3 is just does the repeated dot.

For larger n, it does a binary decomposition to reduce the total number of dots. I assume that means for n=4:

result = np.dot(M,M)
result = np.dot(result,result)

The sparse version isn't as general. It can only handle positive integer powers.

You can't count on numpy functions operating on spare matrices. The ones that do work are the ones that pass the action on to the array's own method. e.g. np.sum(A) calls A.sum().

You can also use ** notation instead of matrix_power for numpy matrix :

a=np.matrix([[1,2],[2,1]])
a**3

Out :

matrix([[13, 14],
        [14, 13]])

try it with scipy sparse matrix.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!