Fit isotonic regression with the pool adjacent violators algorithm

HardRegressionPro

Why it matters Isotonic calibration turns raw model scores into trustworthy probabilities, and it is also used for monotone dose-response and pricing curves.

Isotonic regression finds the best non-decreasing fit to a sequence, which is how many calibration curves are learned.

Write isotonic_fit(y, w=None). y is a 1D sequence already ordered by the input feature, w optional positive weights (default all 1). Return the float array f that minimises sum w_i (y_i - f_i)^2 subject to f_0 <= f_1 <= ... Use pool adjacent violators: scan left to right keeping a stack of blocks (weighted sum, total weight, length); push each point as a new block, and while the last two blocks are out of order (previous mean > last mean), merge them. Finally expand every block to its weighted mean.

Signaturedef isotonic_fit(y, w=None)

Example

y [1, 3, 2, 4, 3, 5] gives [1, 2.5, 2.5, 3.5, 3.5, 5].

Understand the idea

Sometimes we know a relationship only goes up: a higher model score should never mean a lower chance of fraud. Isotonic regression finds the closest staircase that never goes down.

Pool adjacent violators does this greedily. Walk left to right. Whenever a value is lower than the block before it, the two cannot both be right, so we pool them into one block at their average. Pooling can make the block lower, so we check the block before it again.

Worked example: y = 1, 3, 2, 4, 3, 5. 1 is fine. 3 is fine. 2 is below 3, so pool to 2.5, 2.5. 4 is fine. 3 is below 4, pool to 3.5, 3.5. 5 is fine. Result 1, 2.5, 2.5, 3.5, 3.5, 5. For 3, 4, 1: pool 4 and 1 to 2.5, which is now below 3, so pool all three to 2.667.

Rule: merge adjacent blocks while mean(left) > mean(right), using weighted means.

Isotonic calibration is a standard way to fix overconfident classifiers.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

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

  • Sample 1: exampleisotonic_fit([1, 3, 2, 4, 3, 5])
  • Sample 2: cascadeisotonic_fit([3, 4, 1])