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

时间:2020-02-19 16:51:25

标签: python numpy

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)

我想将两个具有不同形状的矩阵相乘,基本上得到一个3d矩阵的结果。我希望您能从代码中得到模式。有什么简单的numpyic方法吗?我会很感激的。

2 个答案:

答案 0 :(得分:1)

您可以为此使用NumPy广播:

a[...,None] * c

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

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

以下基本上保留了尺寸,以便将乘法广播到所需的输出形状:

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

答案 1 :(得分:1)

尝试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)