我正在尝试从此矩阵乘法中删除循环(并了解有关优化代码的更多信息),并且我认为我需要某种形式的np.broadcasting
or np.einsum
,但是在阅读了它们之后,我仍然不确定如何将它们用于我的问题。
A = np.array([[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11,12,13,14,15]])
#A is a 3x5 matrix, such that the shape of A is (3, 5) (and A[0] is (5,))
B = np.array([[1,0,0],
[0,2,0],
[0,0,3]])
#B is a 3x3 (diagonal) matrix, with a shape of (3, 3)
C = np.zeros(5)
for i in range(5):
C[i] = np.linalg.multi_dot([A[:,i].T, B, A[:,i]])
#Each row of matrix math is [1x3]*[3x3]*[3x1] to become a scaler value in each row
#C becomes a [5x1] matrix with a shape of (5,)
我知道我不能自己做np.multidot
,因为这会产生一个 (5,5) 数组。
我还发现了这一点:将矩阵乘以 Numpy 中另一个矩阵的每一行,但我不知道它是否与我的问题相同。