NumPy – What is broadcasting?

The term broadcasting describes how numpy treats arrays with different shapes during arithmetic operations.

It’s basically a way numpy can expand the domain of operations over arrays.

The only requirement for broadcasting is a way aligning array dimensions such that either:

  • Aligned dimensions are equal.
  • One of the aligned dimensions is 1.

So, for example if:

x = np.ndarray(shape=(4,1,3))
y = np.ndarray(shape=(3,3))

You could not align x and y like so:

4 x 1 x 3
3 x 3

But you could like so:

4 x 1 x 3
    3 x 3

How would an operation like this result?

Suppose we have:

x = np.ndarray(shape=(1,3), buffer=np.array([1,2,3]),dtype="int")
array([[1, 2, 3]])

y = np.ndarray(shape=(3,3), buffer=np.array([1,1,1,1,1,1,1,1,1]),dtype="int")
array([[1, 1, 1],
       [1, 1, 1],
       [1, 1, 1]])

The operation x + y would result in:

array([[2, 3, 4],
       [2, 3, 4],
       [2, 3, 4]])

I hope you caught the drift. If you did not, you can always check the official documentation here.

Cheers!

Leave a Comment