Normalize each row of a 2-D array so its entries sum to 1. The interesting part is keepdims=True — without it, the broadcast that follows the reduction silently breaks.
Implement: def row_normalize(x) where x has shape (B, D). Return shape (B, D) where each row sums to 1.
The pattern:
return x / x.sum(axis=-1, keepdims=True)
Why keepdims=True?
x.sum(axis=-1) returns shape (B,) — the feature axis is dropped.x / row_sums is (B, D) / (B,) — by NumPy's right-alignment rule, this aligns B against D. If B != D, error. If B == D (square case), silent shape bug.x.sum(axis=-1, keepdims=True) returns shape (B, 1) — the axis is kept as size 1.x / row_sums is (B, D) / (B, 1) — broadcasts correctly to (B, D).keepdims=True is how you preserve broadcast compatibility after a reduction. This is the single most common bug in handwritten softmax / layernorm / normalize code: forget it, and the output is silently wrong.
Math
Asked at
import numpy as np
def row_normalize(...):
pass
Premium problem
Free accounts include problems #1–20. Upgrade to unlock the editor, hidden test cases, and reference solutions for every problem.
Already premium?