简体   繁体   English

将 3D 矩阵与 2D 矩阵相乘

[英]Multiplying 3D matrix with 2D matrix

I have two matrices to multiply.我有两个矩阵要相乘。 One is the weight matrix W , whose size is 900x2x2 .一种是权重矩阵W ,其大小为900x2x2 Another is input matrix I , whose size is 2x2 .另一个是输入矩阵I ,其大小为2x2

I want to perform a summation over c = WI which will be a 900x1 matrix, but when I perform the operation it multiplies them and gives me a 900x2x2 matrix again.我想对c = WI进行求和,这将是一个900x1 的矩阵,但是当我执行该操作时,它将它们相乘并再次给我一个900x2x2 的矩阵。

Question #2 (related): So I made both of them 2D and multiplied 900x4 * 4x1 , but that gives me an error saying:问题#2(相关):所以我把它们都做成了 2D 并乘以900x4 * 4x1 ,但这给了我一个错误说:

ValueError: operands could not be broadcast together with shapes (900,4) (4,1)

It seems you are trying to lose the last two axes of the first array against the only two axes of the second weight array with that matrix-multiplication.似乎您正试图通过矩阵乘法将第一个数组的最后两个轴与第二个权重数组的唯一两个轴丢失。 We could translate that idea into NumPy code with np.tensordot and assuming arr1 and arr2 as the input arrays respectively, like so -我们可以将这个想法转换成 NumPy 代码,使用np.tensordot并假设arr1arr2分别作为输入数组,如下所示 -

np.tensordot(arr1,arr2,axes=([1,2],[0,1]))

Another simpler way to put into NumPy code would be with np.einsum , like so -放入 NumPy 代码的另一种更简单的方法是使用np.einsum ,就像这样 -

np.einsum('ijk,jk',arr1,arr2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM