Broadcasting

Broadcasting is the process of transforming arrays into same size (shape) to carry out operations like addition, and other operations.

  • Used in arithmetic operations in numpy arrays.
  • Provides a means of vectorizing array operations so that the looping happens inside C instead of python.
  • Applying arithmetic operations on arrays with different shapes and dimensions, the smaller one has to be stretched to make compatible with larger one.

Broadcasting rules

  1. Compatibility checks starts from right to left.
  2. Two dimensions are compatible only when
    1. both are same
    2. either one of them is 1
dims1 = (1,)
dims2 = (1,)
BOTH ARE COMPATIBLE
------------

dims1 = (1,2)
dims2 = (1,1)
BOTH ARE COMPATIBLE as there is 1 in last dimension
------------

dims1 = (1,2)
dims2 = (1,3)
NOT COMPATIBLE as dimensions differ and one of them is not 1
------------

dims1 = (4, 1)
dims2 = (3,)
BOTH ARE COMPATIBLE
as
       4 x 1
       1 x 3
result 4 x 3

items = np.arange(10).reshape((2, 5))
items.shape # (2, 5)
 
mul = np.array([2, 3](2,%203))
mul.shape # (2, 2)
 
items * mul
# ValueError: operands could not be broadcast together with shapes (2,5) (2,2)

References

  1. https://lectures.scientific-python.org/intro/numpy/operations.html#broadcasting