In NumPy, arithmetic operations are done element-wise. To achieve this, arrays should be of the same size/shape.
To perform arithmetic operations on arrays of different sizes/shapes, broadcasting is used.
Imagine that broadcasting means stretching the array to the required shape/size to perform arithmetic operations on it.
Broadcasting Rules:
- The size of each dimension should be the same.
- The size of one of the dimensions should be one.
Scenario 1: Dimensions of both the arrays are the same
Example 1: Two-dimensional arrays
Let’s add two 2-D arrays (a1,a2) of different shapes.
The shape of a1 (2,1)
The shape of a2 (2,2)
a1+a2 → We can perform addition because the broadcast rule matches.
- The first axis is the same
- The second axis is 1 in one of the arrays (a1)
[If the axis are not the same, one of them should be 1]
Example 2: Three-dimensional arrays
Let’s add two 3-D arrays (a1,a2) of different shapes.
The shape of a1 (2,3,1)
The shape of a2 (2,3,2)
a1+a2 → We can perform addition because the broadcast rule matches.
- The first axis is the same
- The second axis is the same
- The third axis is 1 in one of the arrays (a1)
[If the axis are not the same, one of them should be 1]
Scenario 2: Dimensions of both the arrays are different
If the dimensions of the two arrays are different, then the shape of one with fewer dimensions is padded with ones on its leading side (left side)
Example: Let’s add two arrays of different dimensions.
The shape of a1 → (3,2)
The shape of a2 →(2,3,2)
Since dimensions of both arrays (a1,a2) are different, then the shape of a1 (a1 having fewer dimensions than a2) is padded with ones on its leading side (left side)
The shape of a1 becomes → (1,3,2)
[a1 only has fewer dimensions than a2]
Now check the broadcast rules in a1,a2
- The first axis is 1 on one of the arrays (a1)
[If the axis are not the same, one of them should be 1] - The second axis is the same
- The third axis is the same
Now we can perform a1+a2 → because it matches broadcast rules.
If we need to perform arithmetic operations on two arrays of different shapes, then it should match broadcast rules. Otherwise, it will throw an error. (Not able to perform arithmetic operations)
Example:
The shape of a1 (2,3)
The shape of a2 (2,4)
We can’t perform a1+a2, because it doesn’t match broadcast rules.
[Second axis is different and it is not 1 in one of the arrays]