numpy 3darray矩阵乘法功能 [英] Numpy 3darray matrix multiplication function
问题描述
假设我有一个ndarray,W的形状为(m,n,n),向量C的尺寸为(m,n).我需要按以下方式将这两个数相乘
Suppose I have an ndarray, W of shape (m,n,n) and a vector C of dimension (m,n). I need to multiply these two in the following way
result = np.empty(m,n)
for i in range(m):
result[i] = W[i] @ C[i]
我该如何以向量化的方式来执行此操作,而不会出现循环和所有事件?
How do I do this in a vectorized way without loops and all?
推荐答案
自此,您需要使W
和C
的第一个轴保持对齐,同时使用矩阵乘法从它们的最后一个轴上松开,我建议使用 np.einsum
这样非常有效的方法-
Since, you need to keep the first axis from both W
and C
aligned, while loosing the last axis from them with the matrix-multiplication, I would suggest using np.einsum
for a very efficient approach, like so -
np.einsum('ijk,ik->ij',W,C
)
np.tensordot
或np.dot
没有保持轴对齐的功能,这是np.einsum
得以改进的地方.
np.tensordot
or np.dot
doesn't have the feature to keep axes aligned and that's where np.einsum
improves upon.
这篇关于numpy 3darray矩阵乘法功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!