POST 1 of 5 MorningAI/MLConcept
Broadcasting in one rule
Day 30. Broadcasting is one of those topics where ten online tutorials each explain it differently. Most of them overcomplicate it. The actual rule is small. When you do an operation between two arrays of different shapes, NumPy aligns them by: One — pad the shorter shape with leading 1s until both have the same number of dimensions. Two — for each dimension, the sizes must either match, or one of them must be 1. Where one is 1, NumPy 'stretches' it to match the other. If no consistent alignment exists, NumPy raises a ValueError. That's it. Two rules. Pad and stretch. Examples: (3,) + (3,) → (3,). Same shape; element-wise. (3, 4) + (4,). Pad the (4,) to (1, 4). Stretch the leading 1 to 3. Both are now (3, 4). Element-wise. (3, 1) + (1, 4). No padding needed. Stretch the trailing 1 in the first to 4. Stretch the leading 1 in the second to 3. Both become (3, 4). Outer-product-style result. (2, 3, 4) + (4,). Pad (4,) to (1, 1, 4). Stretch to (2, 3, 4). Element-wise. (2, 3, 4) + (3, 1). Pad (3, 1) to (1, 3, 1). Stretch leading 1 to 2; trailing 1 to 4. Result (2, 3, 4). A case that fails — (3,) + (4,). Padding gives (3,) and (4,) — same dim count. Sizes 3 and 4 don't match and neither is 1. ValueError. This rule explains every PyTorch shape error you'll encounter. The framework error message tells you the shapes; you walk through the rule mentally; you find which dim broke. Memorise the rule. It comes up in every NN forward pass.
#NumPy#Pandas#DataScience#Python#100DaysOfCode#Broadcasting