Broadcasting: when shapes stretch
Why it matters Adding a bias to every row worked without a loop. That is broadcasting. It is also behind the most common gradient bug you will meet in Module 4.
When two arrays have different shapes, NumPy lines the shapes up from the right. Each pair of sizes must be equal, or one of them must be 1 (or missing). A size-1 direction is stretched to match.
Tiny numbers
- (3, 4) + (4,) works: the (4,) row is reused for all 3 rows.
- (3, 4) + (3,) fails: lined up from the right, 4 and 3 do not match.
- (3, 4) + (3, 1) works: the column is reused across all 4 columns.
- (5, 1) + (1, 6) gives (5, 6): both stretch.
Broadcasting: NumPy's rule for combining arrays of different shapes by stretching size-1 directions.
Recap Line up from the right; equal or 1, else error.
Words and symbols in this lesson
- broadcasting
- NumPy stretching size-1 directions so arrays of different shapes combine
Write broadcast_shape(s1, s2) that returns the result shape of combining two shapes, or None if they cannot broadcast. Implement the rule yourself (do not call NumPy's helper).
Spotted a problem in this lesson? Report it · Ask about this lesson
This exercise opens soon
Finish the lesson before it and this one unlocks. The whole course is free, no account needed, and you can read this lesson right now.
This browser is blocking cookies for learn.floati.life, so lessons you finished here cannot open in order. Allow cookies for this site and reload.