多维矩阵(/array)的矩阵乘法-如何避免循环? [英] Matrix multiplication for multidimensional matrix (/array) - how to avoid loop?
问题描述
我正在尝试使用包含多个要相乘的矩阵的数组来评估矩阵相乘.可以使用np.dot(或Py3.5 +中的新@运算符)使用两个矩阵轻松实现这一点,但是我一直在努力扩展它以有效地评估我的多维数组.
I'm trying to evaluate a matrix multiplication with arrays containing multiple matrices to be multiplied together. This can easily be achieved with two matrices using np.dot (or the new @ operator in Py3.5 +), but I'm struggling to extend this to efficiently evaluate my multidimensional arrays.
作为一个例子,假设我有形状为(5,3,3)的矩阵A和形状为(5,3)的矩阵B.现在,我想针对每5种情况对多个后继部分进行矩阵处理:即
As an example, let's say I have matrix A with shape (5,3,3) and B with shape (5,3). Now, I want to matrix multiple the later parts for each 5 cases: i.e. do
res[0] = np.dot(A[0], B[0])
res[1] = np.dot(A[1], B[1])
etc
我可以使用循环成功实现此目标-例如:
I can successfully achieve this using a loop - e.g.:
A = np.random.random((5,3,3))
B = np.random.random((5,3))
res = np.zeros([5,3])
for i in range(len(A)):
res[i] = np.dot(A[i], B[i])
尽管这很慢,因为它使用了循环.
althoug this is slow because it uses a loop.
请问有什么功能/方法可以完全矢量化吗?
Is there a function / approach I could take to fully vectorize this please?
谢谢.
推荐答案
您可以使用 np.einsum
-
You can use np.einsum
-
np.einsum('ijk,ik->ij',A,B)
使用 np.matmul
-
np.matmul(A,B[...,None]).squeeze()
np.matmul(A,B[...,None])[...,0]
这篇关于多维矩阵(/array)的矩阵乘法-如何避免循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!