Calibrate classifier scores with Platt scaling

Why it matters SVMs, boosted trees and ranking models output uncalibrated scores, and Platt scaling is the standard quick fix before scores are used as probabilities.

Platt scaling fits a small logistic regression on top of raw scores (for example SVM margins) so they become calibrated probabilities.

Write platt_fit(scores, y, n_iter=50). Model p_i = sigmoid(a * s_i + b). To avoid overfitting use smoothed targets: t_i = (N_pos + 1) / (N_pos + 2) for positives and 1 / (N_neg + 2) for negatives. Minimise the cross-entropy sum -[t_i log p_i + (1 - t_i) log(1 - p_i)] with Newton's method on (a, b), starting from a = 0 and b = log((N_pos + 1) / (N_neg + 1)). Each step uses gradient [sum (p - t) s, sum (p - t)] and Hessian [[sum w s^2, sum w s], [sum w s, sum w]] with w = p (1 - p). Return (a, b) as floats.

Signaturedef platt_fit(scores, y, n_iter=50)

Example

scores [-2, -1, 0, 1, 2, 3], y [0, 0, 1, 0, 1, 1] gives (0.535510, -0.267755) (rounded).

Understand the idea

Many models give scores that rank well but are not probabilities. An SVM margin of 2 does not mean '90% sure'. Platt scaling learns a squashing curve p = sigmoid(a * score + b) on held-out data, so that among items given 0.8, about 80% really are positive.

It is just a tiny logistic regression with one input. Two small tricks make it robust. First, targets are softened: with 3 positives the positive target is (3 + 1) / (3 + 2) = 0.8, and with 3 negatives the negative target is 1 / (3 + 2) = 0.2. This stops the fit from pushing probabilities to exactly 0 or 1 on small or separable sets. Second, b starts at the log odds of the class balance.

Worked example: before any Newton step, with 3 positives and 3 negatives, b = log(4 / 4) = 0 and a = 0, so every p = 0.5. Positives with target 0.8 pull a upward because their scores are larger.

Rule: minimise sum of cross-entropy between t_i and sigmoid(a s_i + b) with Newton steps.

Platt scaling is the usual sigmoid calibration option in ML libraries.

Shapes and data flow

scores (n,) -> p (n,) -> gradient (2,), Hessian (2, 2)
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: exampleplatt_fit([-2, -1, 0, 1, 2, 3], [0, 0, 1, 0, 1, 1])
  • Sample 2: separable stays finiteplatt_fit([-3, -2, -1, 1, 2, 3], [0, 0, 0, 1, 1, 1])