Figuring Out Broadcasting Shape In Numpy
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)
Solution 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)
Solution 2:
The broadcasting rules are:
Addleading singleton dimensions as needed tomatch number of dimensions
Scale any singleton dimensions tomatch 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).
Post a Comment for "Figuring Out Broadcasting Shape In Numpy"