English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

NumPy Broadcasting

NumPy broadcasting is mainly used to handle arrays with different shapes during arithmetic operations. Under certain constraints, the smaller array is 'broadcasted' on the larger array to have compatible shapes.
NumPy operations are usually performed element-wise on array pairs. In the simplest case, two arrays must have the same shape, as shown in the following example:

 >>> import numpy as np
 >>> a = np.array([1, 2, 3))
 >>> b = np.array([2, 2, 2))
 >>> a * b
 array([ 2, 4, 6))

When the operation involves 2 When the shapes of multiple arrays are different, numpy will automatically trigger the broadcasting mechanism. For 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))
 >>> print(a + b)
 [[ 1 2 3]]
  [11 12 13]]
  [21 22 23]]
  [31 32 33]]

The following image shows how array b is broadcasted to be compatible with array a.

4x3 A two-dimensional array with a length of 3 Adding a one-dimensional array is equivalent to repeating array b on two dimensions 4 Repeated computation:

 >>> 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)
 [[ 1 2 3]]
  [11 12 13]]
  [21 22 23]]
  [31 32 33]]

General broadcasting rules

When running on two arrays, NumPy compares their shapes element-wise. It starts from the trailing dimensions and progresses forward. Two sizes are compatible when

They are equal, or
One of which is1

If these conditions are not met, a ValueError: operands could not be broadcast together exception is raised, indicating that the arrays have incompatible shapes. The size of the resulting array is not1in size.

The array does not need to have the same number of dimensions. For example, if you have256x256x3An array of RGB values, and you want to scale each color in the image to a different value, you can multiply the image by an array with3A one-dimensional array of a single value. The sizes of the tail axes of these arrays are arranged according to the broadcasting rules to indicate that they are compatible:

 Image (3d array): 256 x 256 x 3
 Scale (1d array): 3
 Result (3d array): 256 x 256 x 3

When any of the compared dimensions is1When using another size. In other words, the size is1The size is stretched or 'copied' to match another size. In the following example, both arrays A and B have a length of1The axis, which will expand to a larger size during the broadcasting operation:

 A (4d array): 8 x 1 x 6 x 1
 B (3d array): 7 x 1 x 5
 Result (4d array): 8 x 7 x 6 x 5

Here are some examples:

 A (2d array): 5 x 4
 B (1d array): 1
 Result (2d array): 5 x 4
 A (2d array): 5 x 4
 B (1d array): 4
 Result (2d array): 5 x 4
 A (3d array): 15 x 3 x 5
 B (3d array): 15 x 1 x 5
 Result (3d array): 15 x 3 x 5
 A (3d array): 15 x 3 x 5
 B (2d array): 3 x 5
 Result (3d array): 15 x 3 x 5
 A (3d array): 15 x 3 x 5
 B (2d array): 3 x 1
 Result (3d array): 15 x 3 x 5

Here are some examples of shapes that are not broadcasted:

 A (1d array): 3
 B (1d array): 4 #The trailing dimensions do not match
 A (2d array): 2 x 1
 B (3d array): 8 x 4 x 3 #The second-to-last dimension does not match

An example of broadcasting in practice:}

 >>> import numpy as np
 >>> x = np.arange(4)
 >>> xx = x.reshape(4,1)
 >>> y = np.ones(5)
 >>> z = np.ones((3,4))
 >>> x.shape
 (4,)
 y.shape
 (5,)
 >>> x + y
 ValueError: operands could not be broadcast together with shapes (4,) (5,)
 >>> xx.shape
 (4, 1)
 y.shape
 (5,)
 >>> (xx + y).shape
 (4, 5)
 >>> xx + y
 array([[ 1., 1., 1., 1., 1.],
        [ 2., 2., 2., 2., 2.],
        [ 3., 3., 3., 3., 3.],
        [ 4., 4., 4., 4., 4.]])
 >>> x.shape
 (4,)
 >>> z.shape
 (3, 4)
 >>> (x + z).shape
 (3, 4)
 >>> x + z
 array([[ 1., 2., 3., 4.],
        [ 1., 2., 3., 4.],
        [ 1., 2., 3., 4.]])

Broadcasting provides a convenient way to obtain the outer product (or any other outer operation) of two arrays. The following examples show two1-Outer product operation of d array:

 >>> import numpy as np
 >>> a = np.array([0.0, 10.0, 20.0, 30.0])
 >>> b = np.array([1.0, 2.0, 3.0])
 >>> a[:, np.newaxis] + b
 array([[ 1., 2., 3.],
        [ 11., 12., 13.],
        [ 21., 22., 23.],
        [ 31., 32., 33.]])

here newaxisindex operator to insert a new axis a , to make it a two-dimensional 4x1array. Convert 4x1array with shape (3,)of bcombination, to produce a 4x3Array.