简体   繁体   English

形状为(N,M)和(N,)的数组之间的广播操作

[英]Broadcast operation between arrays of shape (N, M) and (N,)

This is a rather simple question but I can't seem to find the answer. 这是一个相当简单的问题,但我似乎找不到答案。 Consider two simple arrays: 考虑两个简单的数组:

import numpy as np
a = np.random.uniform(0., 1., (2, 1000))
b = np.random.uniform(0., 1., (2,))

I want to perform the operation a - b so that the final array is ([[a[0] - b[0], a[1] - b[1]]) and I get 我想要执行操作a - b以便最终数组为([[a[0] - b[0], a[1] - b[1]]) ,我得到

ValueError: operands could not be broadcast together with shapes (2,1000) (2,) 

How can I perform this (or some other) operation? 如何执行此(或其他)操作?

According to the General Broadcasting Rules : 根据一般广播规则

When operating on two arrays, NumPy compares their shapes element-wise. 在两个数组上进行操作时,NumPy逐元素比较其形状。 It starts with the trailing dimensions, and works its way forward. 它从尾随尺寸开始,一直向前发展。 Two dimensions are compatible when 两种尺寸兼容

  1. they are equal, or 它们相等,或者
  2. one of them is 1 其中之一是1

So there's the error because the last dimension of a (1000) and b (2) can not be broadcasted; 出现错误是因为无法广播a (1000)和b (2)的最后维度; You can convert b to a 2d array of shape (2, 1) so that 1 -> (can broadcast to) 1000 , 2 -> (can broadcast to) 2 : 你可以转换b到形状的2D阵列(2, 1)使得1 - >(可广播到) 10002 - >(可广播到) 2

a - b[:,None]                            
#array([[ 0.06475683, -0.43773571, -0.62561564, ...,  0.05205518,
#        -0.1209487 ,  0.16334639],
#       [ 0.58443617,  0.28764136,  0.75789299, ...,  0.18159133,
#         0.28548633, -0.12037869]])

Or 要么

a - b.reshape(2,1)

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

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