NumPy Broadcasting

In Mathematical operations, we may need to consider the arrays of different shapes. NumPy can perform such operations where the array of different shapes are involved.

For example, if we consider the matrix multiplication operation, if the shape of the two matrices is the same then this operation will be easily performed. However, we may also need to operate if the shape is not similar.

Consider the following example to multiply two arrays.

Example

Output:

[ 2  8 18 32 50 72 98]

However, in the above example, if we consider arrays of different shapes, we will get the errors as shown below.

Example

Output:

ValueError: operands could not be broadcast together with shapes (7,) (8,) 

In the above example, we can see that the shapes of the two arrays are not similar and therefore they cannot be multiplied together. NumPy can perform such operation by using the concept of broadcasting.

In broadcasting, the smaller array is broadcast to the larger array to make their shapes compatible with each other.

Broadcasting Rules

Broadcasting is possible if the following cases are satisfied.

  1. The smaller dimension array can be appended with '1' in its shape.
  2. Size of each output dimension is the maximum of the input sizes in the dimension.
  3. An input can be used in the calculation if its size in a particular dimension matches the output size or its value is exactly 1.
  4. If the input size is 1, then the first data entry is used for the calculation along the dimension.

Broadcasting can be applied to the arrays if the following rules are satisfied.

  1. All the input arrays have the same shape.
  2. Arrays have the same number of dimensions, and the length of each dimension is either a common length or 1.
  3. Array with the fewer dimension can be appended with '1' in its shape.

Let's see an example of broadcasting.

Example

Output:

printing array a..
[[ 1  2  3  4]
 [ 2  4  5  6]
 [10 20 39  3]]

printing array b..
[2 4 6 8]

Adding arrays a and b ..
[[ 3  6  9 12]
 [ 4  8 11 14]
 [12 24 45 11]]
NumPy Broadcasting




Latest Courses