Broadcasting is a feature in NumPy that allows arithmetic operations to be performed on arrays with different shapes. In general, two arrays are compatible for broadcasting if their shapes are equal or if one of them has a dimension of size 1.
The broadcasting rules in NumPy are as follows:
If the arrays have different numbers of dimensions, the shape of the array with fewer dimensions is padded with ones on its leading (left) side.
If the shape of the arrays does not match in any dimension, the array with shape equal to 1 in that dimension is stretched to match the shape of the other array.
If the shape of the arrays does not match in any dimension and neither is equal to 1, then a ValueError is raised.
Here are some examples that illustrate these rules:
import numpy as np# 1. Broadcasting with arrays of different numbers of dimensionsx = np.array([1, 2, 3])y = np.array([[1], [2], [3]])# x has shape (3,) and y has shape (3, 1)# We can broadcast y along the second dimension to obtain a shape of (3, 3)# And then add the two arrays element-wisez = x + yprint(z)# Output: [[2 3 4]# [3 4 5]# [4 5 6]]# 2. Broadcasting with arrays of different shapesx = np.array([1, 2, 3])y = np.array([[1, 2, 3], [4, 5, 6]])# x has shape (3,) and y has shape (2, 3)# x can be broadcast along the first dimension to obtain a shape of (2, 3)# And then add the two arrays element-wisez = x + yprint(z)# Output: [[2 4 6]# [5 7 9]]# 3. Broadcasting with incompatible shapesx = np.array([1, 2, 3])y = np.array([4, 5, 6, 7])# x has shape (3,) and y has shape (4,)# The arrays cannot be broadcast because they do not match in any dimension# A ValueError is raisedz = x + y# Output: ValueError: operands could not be broadcast together with shapes (3,) (4,) |
Broadcasting can be very useful for simplifying code and avoiding unnecessary reshaping of arrays. However, it is important to use it judiciously to ensure that the results are correct and that the code is easy to read and understand.