Broadcasting

Giới thiệu về NumPy

Izzy Weber

Core Curriculum Manager, DataCamp

Broadcasting introduced

 

A graphic showing two arrays with different shapes begin added together

Giới thiệu về NumPy

Broadcasting a scalar

Image showing a 2D array being added to the number 2  

Image showing a 2D array being added to any array full of twos which has the same shape

Giới thiệu về NumPy

Compatibility rules

  • NumPy compares sets of array dimensions from right to left  

 

 

 

 

A graphic applying the compatibility rules to arrays shapes of (10, 5 and (10, 1))

Giới thiệu về NumPy

Compatibility rules

  • NumPy compares sets of array dimensions from right to left
  • Two dimensions are compatible when...
    • One of them has a length of one or
    • They are of equal lengths
  • All dimension sets must be compatible

 

A graphic applying the compatibility rules to arrays shapes of (10, 5 and (10, 1))

Giới thiệu về NumPy

Broadcastable or not?

 

Broadcastable shapes:

  • (10, 5) and (10, 1)
  • (10, 5) and (5, )

 

Shapes which are not broadcastable:

  • (10, 5) and (5, 10)
  • (10, 5) and (10, )
Giới thiệu về NumPy

Broadcasting rows

An array with shape (2, 5) being added to an array with shape (1, 5)

 

array = np.arange(10).reshape((2, 5))
array + np.array([0, 1, 2, 3, 4])
array([[ 0,  2,  4,  6,  8],
       [ 5,  7,  9, 11, 13]])
Giới thiệu về NumPy

Broadcasting rows

 

 

An array with shape (2, 5) being added to an array with shape (2, 5)

Giới thiệu về NumPy

Incompatible broadcasting

 

A graphic showing that adding an array of shape (2, 5) to one of shape (2,) generates a ValueError.

 

array = np.arange(10).reshape((2, 5))
array + np.array([0, 1])
ValueError: operands could not be broadcast together with shapes (2,5) (2,) 
Giới thiệu về NumPy

Broadcasting columns

A graphic showing an array of shape (2, 5) and one of shape (2, 1) being added together

array = np.arange(10).reshape((2, 5))
array + np.array([0, 1]).reshape((2, 1))
array([[ 0,  1,  2,  3,  4],
       [ 6,  7,  8,  9, 10]])
Giới thiệu về NumPy

Broadcasting columns

 

 

A graphic showing the single-column array stretched column-wise across an array with the same shape as the larger array

Giới thiệu về NumPy

Other operators

An array with shape (2, 2) being multiplied by an array with shape (2, 1)

An array with shape (2, ) being subtracted from an array with shape (2, 2)

Giới thiệu về NumPy

Let's practice!

Giới thiệu về NumPy

Preparing Video For Download...