python矩阵乘法分治_numpy的大矩阵乘法优化

I have to do a iterative calculation with large matrix:

R(t) = M @ R(t-1), where M is n x n, and R is n x 1

if I write this:

for _ in range(iter_num):

R = M @ R

I suppose it will be very slow, because it has to copy and create new array each time. Is that any way to optimize this? (maybe do it inplace?)

解决方案

A few timings to show that OP's approach is actually quite competitive:

>>> import functools as ft

>>> kwds = dict(globals=globals(), number=1000)

>>> R = np.random.random((200,))

>>> M = np.random.random((200, 200))

>>> def f_op(M, R):

... for i in range(k):

... R = M@R

... return R

...

>>> def f_pp(M, R):

... return ft.reduce(np.matmul, (R,) + k * (M.T,))

...

>>> def f_ag(M, R):

... return np.linalg.matrix_power(M, k)@R

...

>>> def f_tai(M, R):

... return np.linalg.multi_dot([M]*k+[R])

...

>>> k = 20

>>> repeat('f_op(M, R)', **kwds)

[0.14156094897771254, 0.1264056910004001, 0.12611976702464744]

>>> repeat('f_pp(M, R)', **kwds)

[0.12594187198556028, 0.1227772050187923, 0.12045996301458217]

>>> repeat('f_ag(M, R)', **kwds)

[2.065609384997515, 2.041590739012463, 2.038702343008481]

>>> repeat('f_tai(M, R)', **kwds)

[3.426795684004901, 3.4321794749994297, 3.4208814119920135]

>>>

>>> k = 500

>>> repeat('f_op(M, R)', **kwds)

[3.066054102004273, 3.0294102499901783, 3.020273027010262]

>>> repeat('f_pp(M, R)', **kwds)

[2.891954762977548, 2.8680382019956596, 2.8558325179910753]

>>> repeat('f_ag(M, R)', **kwds)

[5.216210452985251, 5.1636185249954, 5.157578871003352]

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值