Divide arrays safely with a fill value where the denominator is zero

Why it matters Safe division shows up in masked losses, per-class metrics and normalizing counts in every ML codebase.

Per-sequence averages, precision and token-normalized losses all divide by counts that can be zero. A safe divide returns a chosen fill value there, with no inf, nan or warning.

Write safe_ratio(num, den, fill=0.0). num and den are arrays that broadcast together (for example (B, T) and (B, 1)). Return a float array of the broadcast shape equal to num / den where den != 0, and fill where den == 0.

Signaturedef safe_ratio(num, den, fill=0.0)

Example

safe_ratio([4.0, 1.0, 5.0], [2.0, 0.0, 5.0]) is [2.0, 0.0, 1.0].

Understand the idea

Dividing by zero in NumPy gives inf or nan and a warning. A safe divide decides up front what the answer should be where the denominator is zero, and only divides elsewhere. Broadcasting lets a (B, 1) column of counts divide every column of a (B, T) array.

Worked example: num [4, 1, 5] and den [2, 0, 5]. Cells 0 and 2 have den != 0: 4 / 2 = 2.0 and 5 / 5 = 1.0. Cell 1 has den = 0, so it gets the fill 0.0. Result [2.0, 0.0, 1.0]. Replacing 0 with 1 would give 1 / 1 = 1.0 there, a fake value.

Rule: out = fill everywhere, then out[den != 0] = num / den on those cells. np.divide(num, den, out=out, where=den != 0) does it in one call.

Masked token losses, per-class recall and averages over empty batches all need this.

Shapes and data flow

num (B, T), den (B, 1) -> out (B, T)
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: examplesafe_ratio([4.0, 1.0, 5.0], [2.0, 0.0, 5.0])
  • Sample 2: broadcast rowssafe_ratio([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]], [[2.0], [0.0], [4.0]], -1.0)
  • Test 3: all zero denominatorssafe_ratio([1.0, 2.0], [0.0, 0.0], 9.0)