NumPy Broadcasting

Broadcasting is numpy's way of performing numerical calculations on arrays of different shapes. Arithmetic operations on arrays are usually performed on corresponding elements.

If two arrays a and b have the same shape, i.e., satisfya.shape == b.shape, then the result of a*b is the multiplication of the corresponding elements of a and b. This requires the same number of dimensions and the same length in each dimension.

Example

import numpy as np a = np.array([1,2,3,4]) b = np.array([10,20,30,40]) c = a * b print (c)

The output result is:

[ 10  40  90 160]

When the shapes of the 2 arrays in an operation are different, numpy automatically triggers the broadcasting mechanism. For example:

Example

import numpy as np a = np.array([[ 0, 0, 0], [10,10,10], [20,20,20], [30,30,30]]) b = np.array([0,1,2]) print(a + b)

The output result is:

[[ 0  1  2]
 [10 11 12]
 [20 21 22]
 [30 31 32]]
The image below shows how array b is made compatible with array a through broadcasting.

Adding a 4x3 two-dimensional array to a one-dimensional array of length 3 is equivalent to repeating array b 4 times in the second dimension and then performing the operation:

Example

import numpy as np a = np.array([[ 0, 0, 0], [10,10,10], [20,20,20], [30,30,30]]) b = np.array([1,2,3]) bb = np.tile(b, (4, 1)) # Repeat each dimension of b print(a + bb)

The output result is:

[[ 1  2  3]
 [11 12 13]
 [21 22 23]
 [31 32 33]]

Broadcasting rules:

  • Let all input arrays align with the array that has the most dimensions among them; the missing parts of the shape are filled by adding 1s in front.
  • The shape of the output array is the maximum of the input array shapes along each dimension.
  • If the length of a dimension of an input array is the same as the corresponding dimension of the output array, or its length is 1, then the array can be used for computation; otherwise, an error occurs.
  • When the length of a dimension of an input array is 1, the first set of values in that dimension is used for operations along that dimension.

Simple understanding:For two arrays, compare each of their dimensions (ignore if one array does not have the current dimension), and the following conditions must be satisfied:

  • The arrays have the same shape.
  • The value of the current dimension is equal.
  • One of the values of the current dimension is 1.

If the conditions are not satisfied, throw"ValueError: frames are not aligned"an exception.

Other extensions