Put a Wilson score confidence interval on a success rate
Why it matters Wilson intervals are the safe default for reporting pass rates on small eval sets, click-through rates and conversion rates, and for ranking items by rating.
The textbook p +/- z * sqrt(p (1 - p) / n) interval breaks for small n or rates near 0 and 1 (it can even go below 0). The Wilson interval fixes that.
Write wilson_interval(k, n, z=1.96). k successes out of n trials. With p = k / n, center = (p + z^2 / (2n)) / (1 + z^2 / n) and half = z * sqrt(p (1 - p) / n + z^2 / (4 n^2)) / (1 + z^2 / n). Return (center - half, center + half) as floats. If n is 0, return (0.0, 1.0).
def wilson_interval(k, n, z=1.96)Example
k 8, n 10 gives (0.490157, 0.943319) (rounded).
Understand the idea
If a model passes 8 of 10 tests, the true pass rate is probably not exactly 80%. A confidence interval gives the range of believable values. The simple formula p +/- 1.96 sqrt(p(1 - p)/n) misbehaves for small n: for 0 of 20 it says the rate is exactly 0 with no doubt at all.
The Wilson interval pulls the center slightly toward 50% and keeps some width even at 0 or n successes.
Worked example: k = 8, n = 10, z = 1.96, so z^2 = 3.84. den = 1 + 0.384 = 1.384. center = (0.8 + 0.192) / 1.384 = 0.717. half = 1.96 * sqrt(0.016 + 0.0096) / 1.384 = 1.96 * 0.16 / 1.384 = 0.227. Interval about [0.49, 0.94]. The simple formula would give [0.55, 1.05], going above 100%.
Rule: center = (p + z^2/2n) / (1 + z^2/n), half = z sqrt(p(1 - p)/n + z^2/4n^2) / (1 + z^2/n).
Sites that rank items by rating often sort by the Wilson lower bound.