简体   繁体   English

Numpy 二维数组和长一维数组的乘积,结果应该是 3d 数组

[英]Numpy product of 2d array and a long 1d array, result should be a 3d array

Given two arrays, a and b, with shapes;给定两个arrays,a和b,有形状; (3, 3) and (1000,). (3, 3) 和 (1000,)。 How do I multiply them to get an array with shape (3, 3, 1000)?如何将它们相乘以获得形状为 (3, 3, 1000) 的数组?

a = np.array([[1,2,3],[4,5,6],[7,8,9]])
b = np.linspace(1, 1000, 1000)

c = a * b # does not work
c = np.outer(a, b) # does not work
c = np.outer(a, b[None,] # nope

I have tried a lot of things, too many to remember them all.我尝试了很多东西,太多了,无法全部记住。

I have also googled (and searched on SO) but to no avail.我也用谷歌搜索(并在 SO 上搜索)但无济于事。

IIUC, use numpy.einsum : IIUC,使用numpy.einsum

c = np.einsum("ij,k->ijk", a, b)

Output: Output:

c.shape
# (3, 3, 1000)

You can do it with multiplication by reshaping your arrays:您可以通过重塑 arrays 来进行乘法运算:

M,N = a.shape
B = b.size
c = a.reshape(M,N,1) * b.reshape(1,1,B)
print(c.shape)
print(c[:,:,0])
print(c[:,:,B-1])

Output: Output:

% python3 script.py
(3, 3, 1000)
[[1. 2. 3.]
 [4. 5. 6.]
 [7. 8. 9.]]
[[1000. 2000. 3000.]
 [4000. 5000. 6000.]
 [7000. 8000. 9000.]]

You need to understand the broadcasting rules .您需要了解广播规则 The bottomline is:底线是:

  • both arrays need to have the same number of axes and arrays 都需要具有相同数量的轴和
  • the sizes along each axis must be the same or one of them must be 1.沿每个轴的尺寸必须相同或其中之一必须为 1。

You can multiply and array with shape (3,3) only by another with shape (3,3), (3,1) or (1,3).您只能将形状 (3,3) 与形状 (3,3)、(3,1) 或 (1,3) 的另一个相乘和排列。 There are other broadcasting rules.还有其他广播规则。 Read them.阅读它们。

Your shapes are (3,3) and (1000,).你的形状是 (3,3) 和 (1000,)。 As you said, you need the final shape to be 3-dimensional.正如你所说,你需要最终的形状是 3 维的。 The 3 needs to match an axis with length 1. Same with the 1000 . 3需要匹配长度为 1 的轴。与1000相同。 So you can add axes to each to end up with shapes (3, 3, 1) and (1, 1, 1000):因此,您可以向每个轴添加轴,最终得到形状 (3, 3, 1) 和 (1, 1, 1000):

c = a[:, :, np.newaxis]* b[np.newaxis,np.newaxis]

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

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