python求因子即因子和_加快用于计算矩阵辅因子的python代码

As part of a complex task, I need to compute matrix cofactors. I did this in a straightforward way using this nice code for computing matrix minors. Here is my code:

def matrix_cofactor(matrix):

C = np.zeros(matrix.shape)

nrows, ncols = C.shape

for row in xrange(nrows):

for col in xrange(ncols):

minor = matrix[np.array(range(row)+range(row+1,nrows))[:,np.newaxis],

np.array(range(col)+range(col+1,ncols))]

C[row, col] = (-1)**(row+col) * np.linalg.det(minor)

return C

It turns out that this matrix cofactor code is the bottleneck, and I would like to optimize the code snippet above. Any ideas as to how to do this?

解决方案

If your matrix is invertible, the cofactor is related to the inverse:

def matrix_cofactor(matrix):

return np.linalg.inv(matrix).T * np.linalg.det(matrix)

This gives large speedups (~ 1000x for 50x50 matrices). The main reason is fundamental: this is an O(n^3) algorithm, whereas the minor-det-based one is O(n^5).

This probably means that also for non-invertible matrixes, there is some clever way to calculate the cofactor (i.e., not use the mathematical formula that you use above, but some other equivalent definition).

If you stick with the det-based approach, what you can do is the following:

The majority of the time seems to be spent inside det. (Check out line_profiler to find this out yourself.) You can try to speed that part up by linking Numpy with the Intel MKL, but other than that, there is not much that can be done.

You can speed up the other part of the code like this:

minor = np.zeros([nrows-1, ncols-1])

for row in xrange(nrows):

for col in xrange(ncols):

minor[:row,:col] = matrix[:row,:col]

minor[row:,:col] = matrix[row+1:,:col]

minor[:row,col:] = matrix[:row,col+1:]

minor[row:,col:] = matrix[row+1:,col+1:]

...

This gains some 10-50% total runtime depending on the size of your matrices. The original code has Python range and list manipulations, which are slower than direct slice indexing. You could try also to be more clever and copy only parts of the minor that actually change --- however, already after the above change, close to 100% of the time is spent inside numpy.linalg.det so that furher optimization of the othe parts does not make so much sense.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值