2

I recently ran into the following issue with broadcasting with numpy.

y = randn(100)
x = randn(100,1)
(y+x).shape
> 100,100 

While I realize that this is according to the rules of https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html, it seems to be counter intuitive to what one would expect - that the result be a (100,1) vector.

I was just wondering - is there a good reason for this behavior (i.e. this is behavior desirable) - or is it just a by product of the way broadcasting rules are defined.

1
  • y + x.T may give you what you want. Nov 29, 2016 at 13:06

1 Answer 1

3

The basic idea is that when one or the other array requires iteration for the result shapes to make sense, then you iteratively perform the operation for each entry of the major axis (Separately, NumPy offers ways to cause the iteration to happen over different axes if desired, such as with einsum).

In this case, x has 100 different things along its major axis, each of which is individually added to y. Let's take just the first value x[0] and add it to y. Now we're talking about y having 100 things that are iteratively added to x[0], so the result is a shape-of-y thing. Repeat this for x[1] and so forth.

If you do x.T, then along x's major axis there is just 1 thing, namely a length-100 "row". So then it can be elementwise added to y without modification, so no more broadcasting is needed and you get the "naive" vector math operation you might have had in mind.

NumPy's broadcasting rules are trying to be effective for programming and iteration across a wide swath of possible calculations and operations, many having absolutely nothing to do with linear algebra or common vector/matrix operations. So broadcasting doesn't always (and shouldn't always) assume things in order to privilege the linear algebra sort of expectation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.