将3D矩阵与2D矩阵相乘 [英] Multiplying 3D matrix with 2D matrix

查看:99
本文介绍了将3D矩阵与2D矩阵相乘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个要相乘的矩阵.一个是权重矩阵-W,其大小为 900x2x2 . 另一个是输入矩阵-I,其大小为 2x2 . 现在,我想对c = WI进行求和,这将是 900x1 矩阵, 但是当我执行该操作时,它会相乘并再次给出 900x2x2 矩阵.

I have two matrices to multiply. One is weight matrix - W whose size is 900x2x2. Another is input matrix-I whose size is 2x2. Now I want to perform summation over c = WI which will be 900x1 matrix, but when I perform the operation it multiplies and gives me 900x2x2 matrix again.

Q 2)(相关)所以我将它们都做成2D并乘以900x4 * 4x1,但这给了我一个错误,说

Q 2) (related) So I made both of them 2D and multiplied 900x4 * 4x1 but that gives me an error saying

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

推荐答案

似乎您正在尝试通过矩阵乘法使第一个数组的最后两个轴相对于第二个权重数组的仅两个轴丢失.我们可以使用 np.tensordot ,并分别假设arr1arr2作为输入数组,就像这样-

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 -

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

放入NumPy代码的另一种更简单的方法是使用 np.einsum ,就像这样-

Another simpler way to put into NumPy code would be with np.einsum, like so -

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

这篇关于将3D矩阵与2D矩阵相乘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆