Broadcasting lets us do math on arrays of different shapes easily. It saves time and code by automatically expanding smaller arrays.
Broadcasting with higher dimensions in NumPy
result = array1 + array2
Arrays must be compatible in shape following broadcasting rules.
Smaller arrays are 'stretched' without copying data.
import numpy as np # 2D array plus 1D array A = np.array([[1, 2, 3], [4, 5, 6]]) b = np.array([10, 20, 30]) result = A + b print(result)
import numpy as np # 3D array plus 2D array A = np.ones((2, 3, 4)) B = np.arange(3).reshape(3, 1) result = A + B print(result.shape)
import numpy as np # 4D array plus 1D array A = np.zeros((2, 3, 4, 5)) B = np.array([1, 2, 3, 4, 5]) result = A + B print(result.shape)
This example adds a 2D array to a 3D array. The 2D array is broadcast across the last two dimensions of the 3D array. This means each 3x4 block in the 3D array has the 2D array added to it row-wise.
import numpy as np # Create a 3D array (2 blocks, 3 rows, 4 columns) array_3d = np.arange(24).reshape(2, 3, 4) # Create a 2D array (3 rows, 1 column) array_2d = np.array([[100], [200], [300]]) # Add 2D array to 3D array using broadcasting result = array_3d + array_2d print("3D array shape:", array_3d.shape) print("2D array shape:", array_2d.shape) print("Result shape:", result.shape) print("Result array:") print(result)
Broadcasting does not copy data, so it is memory efficient.
Shapes are compared from right to left when broadcasting.
If dimensions are not compatible, NumPy will raise an error.
Broadcasting lets you do math on arrays with different shapes easily.
Smaller arrays are stretched to match bigger ones without copying data.
This works well with higher dimensional data like images or time series.
Practice
Solution
Step 1: Understand broadcasting concept
Broadcasting lets NumPy perform operations on arrays with different shapes by stretching the smaller array without copying data.Step 2: Compare options with concept
Only Perform element-wise operations by stretching smaller arrays to match larger ones correctly describes this behavior. Options B, C, and D are incorrect because broadcasting does not copy data explicitly, does not require same shape, and does not convert arrays to lists.Final Answer:
Perform element-wise operations by stretching smaller arrays to match larger ones -> Option BQuick Check:
Broadcasting = Stretch smaller arrays [OK]
- Thinking broadcasting copies data
- Believing arrays must have same shape
- Confusing broadcasting with data type conversion
Solution
Step 1: Check broadcasting rules for each dimension
Shapes (3,1,5) and (1,4,5) can broadcast because dimensions are compatible: 3 vs 1, 1 vs 4, 5 vs 5.Step 2: Verify other options
Options A, B, and D have incompatible dimensions that cannot be broadcast for element-wise addition.Final Answer:
(3, 1, 5) and (1, 4, 5) -> Option CQuick Check:
Broadcast compatible shapes = (3,1,5) & (1,4,5) [OK]
- Ignoring dimension order when checking compatibility
- Assuming all different shapes can broadcast
- Confusing shape sizes in different axes
import numpy as np A = np.ones((2, 3, 1)) B = np.arange(4).reshape(1, 1, 4) C = A + B print(C.shape)
Solution
Step 1: Analyze shapes of A and B
A has shape (2, 3, 1), B has shape (1, 1, 4). Broadcasting rules allow these to combine because 1 can stretch to 2 and 3, and 1 can stretch to 4.Step 2: Determine resulting shape
The result shape is the maximum along each dimension: max(2,1)=2, max(3,1)=3, max(1,4)=4, so (2, 3, 4).Final Answer:
(2, 3, 4) -> Option DQuick Check:
Broadcast result shape = (2,3,4) [OK]
- Confusing which dimension broadcasts to which
- Expecting error instead of broadcasting
- Mixing up shape order
import numpy as np X = np.ones((3, 1, 2)) Y = np.ones((2, 3)) Z = X + Y
Solution
Step 1: Compare shapes for broadcasting
X shape is (3,1,2), Y shape is (2,3). Aligning from right: 2 vs 3 (mismatch), 1 vs 2 (mismatch), 3 vs missing dimension.Step 2: Conclude broadcasting compatibility
Dimensions do not match or equal 1, so broadcasting fails and raises an error.Final Answer:
Shapes (3,1,2) and (2,3) cannot be broadcast together -> Option AQuick Check:
Broadcast error due to incompatible shapes [OK]
- Assuming automatic reshaping without explicit code
- Ignoring dimension order in broadcasting
- Thinking data types cause this error
data with shape (10, 1, 5) representing 10 samples, 1 channel, and 5 features. You want to add a bias vector of shape (5,) to each sample and channel. Which code correctly applies broadcasting to add the bias to data?Solution
Step 1: Understand required bias shape and broadcasting
data shape (10,1,5). Bias vector shape (5,) pads with 1s on left to (1,1,5) and broadcasts correctly across samples and channels.Step 2: Evaluate each option
A: bias shape (5,), correct. B: shape (1,5) also broadcasts correctly, but is redundant. C: shape (5,1) incompatible. D: shape (1,1,5) also broadcasts correctly, but is more verbose.Final Answer:
bias = np.array([1,2,3,4,5])
data + bias -> Option AQuick Check:
(10,1,5) + (5,) -> broadcasts OK
- Using 1D bias without extra dimensions
- Wrong reshape causing shape mismatch
- Assuming automatic dimension expansion without reshape
Ready to prove it?
Pass the test and this pattern moves unknown
