【问题标题】:How to multiply matrices n-times?如何将矩阵乘以 n 次?
【发布时间】:2021-10-10 00:25:28
【问题描述】:

我遇到了一个问题。我正在尝试做一些矩阵运算,我必须将几个矩阵相乘,它们包含在一个列表中,但是矩阵的数量是一个可以在代码开头选择的变量。

有没有一种有效的方法可以将多个矩阵相乘,而不是像 in 那样写 n 次

M.append(np.linalg.multi_dot([a[0], a[1], a[2], a[3]]))

谢谢!

【问题讨论】:

  • 我们能看一些相关的代码吗?
  • 使用 for 循环?
  • 我试过循环,但是如何将第 (n+1) 个矩阵乘以循环中的结果 A *B?

标签: python matrix multiplication


【解决方案1】:

这就是multi_dot 的用途。阅读更多here

import numpy as np

A = np.random.random((10000, 100))
B = np.random.random((100, 1000))
C = np.random.random((1000, 5))
D = np.random.random((5, 333))

list_of_arrays = [A, B, C, D]

# the actual dot multiplication
output = np.linalg.multi_dot(list_of_arrays)
output.shape
(10000, 333)

for loop 的身份执行此操作-

list_of_arrays = [A, B, C, D]

output = A
for i in list_of_arrays[1:]:
    output = output@i        # @= operator not supported yet :(
    
output.shape
(10000, 333)

【讨论】:

  • 谢谢!我实际上尝试了 @= 操作,但遗憾的是它没有工作:p 现在它工作了 :)
  • 很高兴能提供帮助,@= 看起来很酷的表情符号,很想在 python 中使用它。
猜你喜欢
  • 2018-06-03
  • 1970-01-01
  • 1970-01-01
  • 2023-01-19
  • 1970-01-01
  • 2018-02-23
  • 1970-01-01
  • 1970-01-01
  • 2016-10-18
相关资源
最近更新 更多