Loading Page Content...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
Broadcasting is NumPy's most powerful and elegant mechanism. It describes how NumPy treats arrays with different shapes during arithmetic operations. Subject to certain constraints, the smaller array is "broadcast" across the larger array so that they have compatible shapes—without actually copying data in memory.
Consider adding a scalar offset to every row of a matrix, or normalizing columns by subtracting their mean:
Here, the scalar 5 was automatically broadcast across all 9 elements. But what happens when adding a 1D vector to a 2D matrix? What shapes are allowed, and what shapes cause errors?
When operating on two arrays, NumPy compares their shapes element-wise, starting from the trailing (rightmost) dimensions and working backwards to the left.
Two dimensions are compatible if and only if:
If neither condition is met, NumPy raises a: ValueError: operands could not be broadcast together with shapes ...
When either dimension is 1, the array with dimension size 1 acts as if it were stretched along that axis to match the larger dimension.
(3, 3)(3,)Alignment Process:
Output:
What if we want to add a column vector of shape (3, 1) to matrix $A$?
Output:
Broadcasting a column vector of shape (4, 1) with a row vector of shape (1, 3):
Consider:
(3, 4)(3,)Fixing the mismatch: If you intend to add $Y$ to each row along the 3 rows of $X$, reshape $Y$ into a column vector of shape (3, 1):
Does broadcasting allocate memory for the stretched array? No!
NumPy achieves broadcasting by setting the memory stride along the stretched axis to 0. A stride of 0 tells the CPU: "When moving along this dimension, do not advance the memory pointer; re-read the exact same memory address."
This means broadcasting an array of 1000 numbers across 1,000,000 rows consumes zero additional bytes of RAM!
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| Element-Wise Arithmetic & Comparison Operations | Universal Functions (ufuncs), Trigonometry & Logarithms |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.