856. Fix the softmax that returns nan
Why it matters Overflow in softmax is the most common numerical bug in ML code, and the fix is asked in almost every ML coding interview.
The starter code below runs, but it has a realistic bug. Read the spec, find the bug and fix it. Keep the function name and signature.
softmax_rows(x) should return the softmax of each row of a 2D array.
Inputs: x is a list or ndarray of shape (n, k). Values can be very large or very negative (for example 1000.0 or -1000.0).
Return an ndarray of floats with shape (n, k), every row summing to 1, with no nan or inf values. No rounding.
def softmax_rows(x)Example 1
Input: softmax_rows([[1.0, 2.0, 3.0]])
Output: [[0.09, 0.2447, 0.6652]]
Example 2
Input: x = [[1000.0, 1001.0]]
Output: [[0.268941, 0.731059]]
Example 3
Input: x = [[0.0, 0.0], [800.0, 0.0]]
Output: [[0.5, 0.5], [1.0, 0.0]]
Constraints
- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 4 tests to be accepted.
Hint 1
Try the large logits test by hand: what is np.exp(1000.0)?
Hint 2
Softmax is shift invariant per row.
Hint 3
Subtract x.max(axis=1, keepdims=True) before exp.
Common mistakes
- Subtracting the global max instead of the row max (works but hides intent and can underflow other rows).
- Clipping inputs, which changes the answer.
- Forgetting keepdims, which breaks broadcasting.
Understand the idea
exp(1000) overflows to inf, and inf / inf is nan. Softmax does not change if you subtract the same number from every entry of a row, so subtract the row maximum first. Then the largest exponent is exp(0) = 1 and nothing overflows. exp(-1000) underflows to 0 for every entry of a very negative row, which gives 0 / 0; the shift fixes that too.
Shapes and data flow
x: (n, k). The max is taken per row with keepdims=True.