YouTip LogoYouTip

Numpy Broadcast

# NumPy Broadcast Broadcasting is NumPy's way of performing numerical operations on arrays with different shapes. Arithmetic operations on arrays are typically performed element-wise. If two arrays `a` and `b` have the same shape, i.e., `a.shape == b.shape`, then `a * b` results in the element-wise product of `a` and `b`. This requires the number of dimensions to be the same, and the length of each dimension to be the same. ## Example ```python import numpy as np a = np.array([1,2,3,4]) b = np.array([10,20,30,40]) c = a * b print(c) Output: When the two arrays in an operation have different shapes, NumPy automatically triggers the broadcasting mechanism. For example: ## Example ```python 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) Output: [ ] The image below illustrates how array `b` is broadcast to be compatible with array `a`. !(#) 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 before performing the operation: ## Example ```python 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 b along each dimension print(a + bb) Output: [ ] **Rules of Broadcasting:** * All input arrays are aligned with the array having the longest shape. Missing dimensions are padded by adding 1 at the beginning. * The shape of the output array is the maximum value across each dimension of the input array shapes. * An input array can be used for computation if its length in a particular dimension is the same as the output array's corresponding dimension or is 1. Otherwise, an error occurs. * When the length of an input array in a particular dimension is 1, the first value along that dimension is used for all computations along that dimension. **Simple Understanding:** For two arrays, compare each of their dimensions (ignoring a dimension if one array doesn't have it). The following conditions must be met: * The arrays have the same shape. * The values in the current dimension are equal. * One of the values in the current dimension is 1. If the conditions are not met, a **"ValueError: frames are not aligned"** exception is raised.
← Numpy Array ManipulationNumpy Indexing And Slicing β†’