问题
I understand the basics of numpy (Pandas) broadcasting but got stuck on this simple example:
x = np.arange(5)
y = np.random.uniform(size = (2,5))
z = x*y
print(z.shape) #(2,5)
My understanding of the z shape is that you had a (1,5) array multiplied with a (2,5) array, the trailing dimension for 5 is equal so you end up with a 2x5 array. Okay that sounds good. My problem is why is x.shape = (5,)? Isn't it one-dimensional so it's really 1x5?
回答1:
NumPy 1D array like x gives you shape such as (5,) without reshaping. If you want to treat it as 1 column matrix of shape 1x5 then do np.arange(5).reshape(1,5)
回答2:
The broadcasting rules are:
Add leading singleton dimensions as needed to match number of dimensions
Scale any singleton dimensions to match dimension values
Raise error dimensions can't be matched
With your x and y:
(5,) * (2,5)
(1,5) * (2,5) # add the leading 1
(2,5) * (2,5) # scale the 1
=> (2,5)
If y was (5,2), it would raise an error, because (1,5) cannot be paired with (5,2). But (5,1) is ok, because (1,5) * (5,1) => (5,5).
来源:https://stackoverflow.com/questions/53475472/figuring-out-broadcasting-shape-in-numpy