简体   繁体   English

Numpy:如何乘以 (N,N) 和 (N,N,M,M) numpy 数组?

[英]Numpy: How to multiply (N,N) and (N,N,M,M) numpy arrays?

I want to multiply two numpy arrays .我想将两个 numpy 数组相乘。 One numpy array is given by matrix of shape (10, 10) and the other is given by a matrix of matrices, ie shape (10, 10, 256, 256) .一个 numpy 数组由形状(10, 10)的矩阵给出,另一个由矩阵矩阵给出,即形状(10, 10, 256, 256)

I now simply want to multiply each matrix in the second matrix of matrices with the corresponding component in the first matrix.我现在只想将第二个矩阵矩阵中的每个矩阵与第一个矩阵中的相应分量相乘。 For instance, the matrix at position (0, 0) in the second matrix shall be multiplied by the value at position (0, 0) in the first matrix.例如,第二个矩阵中位置 (0, 0) 处的矩阵应乘以第一个矩阵中位置 (0, 0) 处的值。

Intuitively, this is not really complicated, but numpy does not seem to support that.直觉上,这并不复杂,但 numpy 似乎并不支持。 Or at least I am not smart enough to make it work.或者至少我不够聪明,无法让它发挥作用。 The ValueError that is thrown says:抛出的 ValueError 说:

ValueError: operands could not be broadcast together with shapes (10,10) (10,10,256,256) ValueError:操作数无法与形状一起广播 (10,10) (10,10,256,256)

Can anybody of you help me please?你们中的任何人都可以帮助我吗? How can I achieve what I want in a numpyy way.我怎样才能以一种麻木的方式实现我想要的。

You can use the NumPy einsum function, eg, (using zeros arrays as dummies in this example):您可以使用 NumPy einsum函数,例如(在此示例中使用零数组作为虚拟对象):

import numpy as np
x = np.zeros((10, 10))
y = np.zeros((10, 10, 256, 256))
z = np.einsum("ij,ijkm->km", x, y)
print(z.shape)
(256, 256)

See here for a nice description of einsum 's usage.有关einsum用法的详细说明,请参见此处

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

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