将2D矩阵的Numpy矩阵相乘得到3D矩阵 [英] Numpy matrix multiplication of 2d matrix to give 3d matrix
问题描述
我有两个numpy数组,例如
I have two numpy arrays, like
A: = array([[0, 1],
[2, 3],
[4, 5]])
B = array([[ 6, 7],
[ 8, 9],
[10, 11]])
对于A和B的每一行,分别说Ra和Rb,我想计算转置(Ra)* Rb.因此,对于给定的A和B值,我想得到以下答案:
For each row of A and B, say Ra and Rb respectively, I want to calculate transpose(Ra)*Rb. So for given value of A and B, i want following answer:
array([[[ 0, 0],
[ 6, 7]],
[[ 16, 18],
[ 24, 27]],
[[ 40, 44],
[ 50, 55]]])
我已经编写了以下代码:
I have written the following code to do so:
x = np.outer(np.transpose(A[0]), B[0])
for i in range(1,len(A)):
x = np.append(x,np.outer(np.transpose(A[i]), B[i]),axis=0)
有没有更好的方法来完成此任务.
Is there any better way to do this task.
推荐答案
您可以将A
和B
的扩展尺寸与 broadcasting
以获得像这样的矢量化解决方案-
You can use extend dimensions of A
and B
with np.newaxis/None
to bring in broadcasting
for a vectorized solution like so -
A[...,None]*B[:,None,:]
说明: np.outer(np.transpose(A[i]), B[i])
基本上在列版本的A[i]
和B[i]
之间进行逐元素乘法.您要对A
中的所有行重复此操作,以免在B
中相应地更改行.请注意,np.transpose()
似乎没有任何影响,因为np.outer
负责预期的元素级乘法.
Explanation : np.outer(np.transpose(A[i]), B[i])
basically does elementwise multiplications between a columnar version of A[i]
and B[i]
. You are repeating this for all rows in A
against corresoinding rows in B
. Please note that the np.transpose()
doesn't seem to make any impact as np.outer
takes care of the intended elementwise multiplications.
我将用矢量化语言描述这些步骤,并像这样实现-
I would describe these steps in a vectorized language and thus implement, like so -
- 扩展
A
和B
的尺寸以为它们两个形成3D
形状,这样我们在两个扩展版本中都保持axis=0
对齐并保持为axis=0
.因此,我们只能确定最后两个轴. - 要引入元素乘法,请将原始2D版本中的A的 push
axis=1
转换为其3D
版本的axis=1
,从而在axis=2
处创建一个单维度以进行扩展A
的版本. -
A
版本的3D
版本的最后一个单例尺寸必须与B
版本的原始2D
版本中axis=1
版本中的元素对齐,以使broadcasting
发生.因此,扩展版本的B
会将其2D版本中的axis=1
中的元素推入其3D
版本中的axis=2
中,从而为axis=1
创建一个单例尺寸.
- Extend dimensions of
A
andB
to form3D
shapes for both of them such that we keepaxis=0
aligned and keep asaxis=0
in both of those extended versions too. Thus, we are left with deciding the last two axes. - To bring in the elementwise multiplications, push
axis=1
of A in its original 2D version toaxis=1
in its3D
version, thus creating a singleton dimension ataxis=2
for extended version ofA
. - This last singleton dimension of
3D
version ofA
has to align with the elements fromaxis=1
in original2D
version ofB
to letbroadcasting
happen. Thus, extended version ofB
would have the elements fromaxis=1
in its 2D version being pushed toaxis=2
in its3D
version, thereby creating a singleton dimension foraxis=1
.
最后,扩展版本为:A[...,None]
& B[:,None,:]
,乘以谁会给我们带来期望的输出.
Finally, the extended versions would be : A[...,None]
& B[:,None,:]
, multiplying whom would give us the desired output.
这篇关于将2D矩阵的Numpy矩阵相乘得到3D矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!