[英]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)
我想将两个不同形状的矩阵相乘,基本上得到一个 3d 矩阵的结果。 我希望你从代码中得到模式。 有什么简单的numpyic方法吗? 我会很感激。
您可以为此使用 NumPy 广播:
a[...,None] * c
array([[[ 1, 2, 3],
[ 2, 4, 6]],
[[ 3, 6, 9],
[ 4, 8, 12]]])
以下基本上调整了维度,以便将乘法广播到所需的输出形状:
a[...,None].shape
(2, 2, 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.