简体   繁体   English

将 2 个 2d 矩阵相乘并得到一个 3d 矩阵

[英]multiplying 2 2d matrices and get a 3d matrix out

import numpy as np

a = np.array([[1,2],[3,4]])

print(a.shape)

c = np.array([[1,2,3]])

print(c.shape)


#wanted result multiplication of a*c would return 2,2,3 shape matrix

final = np.array([[[1,2,3],[2,4,6]],[[3,6,9],[4,8,12]]])

print(final.shape)
print(final)

I would like to multiply two matrices with different shapes and basically get a result which would be a 3d matrix.我想将两个不同形状的矩阵相乘,基本上得到一个 3d 矩阵的结果。 I hope you get the pattern from the code.我希望你从代码中得到模式。 Is there any simple numpyic way for this?有什么简单的numpyic方法吗? I would appreciate it.我会很感激。

You can use NumPy broadcasting for this:您可以为此使用 NumPy 广播:

a[...,None] * c

array([[[ 1,  2,  3],
        [ 2,  4,  6]],

       [[ 3,  6,  9],
        [ 4,  8, 12]]])

The following basically alings the dimensions so the multiplication is broadcast to the desired output shape:以下基本上调整了维度,以便将乘法广播到所需的输出形状:

a[...,None].shape
(2, 2, 1)

Try np.einsum试试np.einsum

out = np.einsum('ij,kl->klj',c,a)

Out[35]:
array([[[ 1,  2,  3],
        [ 2,  4,  6]],

       [[ 3,  6,  9],
        [ 4,  8, 12]]])

In [36]: out.shape
Out[36]: (2, 2, 3)

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

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