简体   繁体   中英

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

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. 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

So there's the error because the last dimension of a (1000) and b (2) can not be broadcasted; You can convert b to a 2d array of shape (2, 1) so that 1 -> (can broadcast to) 1000 , 2 -> (can broadcast to) 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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