简体   繁体   English

Numpy广播数组

[英]Numpy Broadcasting arrays

As I'm trying to understand broadcasting in python, I'm coming across a shape mismatch error. 当我试图了解python中的广播时,遇到了形状不匹配错误。 I know this means that the arrays I have don't fit in terms of dimension. 我知道这意味着我在尺寸方面不适合使用数组。 My code basically tries to do the following operations on the arrays with the following dimensions: 我的代码基本上尝试对具有以下维的数组执行以下操作:

(256,256,3)*(256,256)+(256,256) (256,256,3)*(256256)+(256256)

I know the problem is in the multiplication. 我知道问题出在乘法中。 I was wondering if there is any way to fix this? 我想知道是否有任何方法可以解决此问题? Can I add an extra dimension to the (256,256) array of the multiplication? 我可以在乘法的(256,256)数组中添加额外的维数吗?

Let's say 比方说

A.shape = (256,256,3)
B.shape = (256,256)
C.shape = (256,256)

NumPy broadcasting adds axes on the left by default, so that would result in B and C being broadcasted to NumPy广播默认情况下在左侧添加轴,因此将导致BC广播到

B.shape = (256,256,256)
C.shape = (256,256,256)

and clearly that does not work and is not what you desire, since there is a shape mismatch with A. 显然这是行不通的,也不是您想要的,因为与A的形状不匹配。

So when you want to add an axis on the right , use B[..., np.newaxis] and C[..., np.newaxis] : 因此,当您想在右侧添加轴时,请使用B[..., np.newaxis]C[..., np.newaxis]

A*B[..., np.newaxis] + C[..., np.newaxis]

B[..., np.newaxis] has shape (256,256,1) , which gets broadcasted to (256,256,3) when multiplied with A , and the same goes for C[..., np.newaxis] . B[..., np.newaxis]形状为(256,256,1) ,当与A相乘时会广播为(256,256,3)C[..., np.newaxis]


B[..., np.newaxis] can also be written as B[..., None] -- since np.newaxis is None . B[..., np.newaxis]也可以写为B[..., None] -因为np.newaxisNone It's a little shorter, but the intent is perhaps not quite as clear. 它稍短一些,但目的可能不太清楚。

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

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