58. 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 1
Input: k 8, n 10
Output: (0.490157, 0.943319) (rounded)
Example 2
Input: k = 0, n = 20
Output: (-1.387779e-17, 0.16113)
Example 3
Input: k = 530, n = 1000
Output: (0.49901, 0.560761)
Constraints
- Python 3 standard library. Code runs in your browser.
- Your code must pass all 4 tests to be accepted.
Hint 1
Compute p, then the shifted center and the half-width; both share the 1 + z^2 / n denominator.
Hint 2
Return (0.0, 1.0) when n is 0.
Hint 3
den = 1 + z^2 / n.
Hint 4
The interval always stays inside [0, 1].
Common mistakes
- Using the Wald interval for small n.
- Reporting 0 out of 20 as exactly 0% with no uncertainty.
- Forgetting the z^2 / (4 n^2) term.
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.
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%.
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.
Companies1
- Microsoft a candidate reported this question Microsoft Machine Learning Engineer Interview Questions | Screna AI
From public interview reports and guides. Not affiliated with or endorsed by these companies.