Sub topic 10
Isotonic regression
Isotonic regression fixes miscalibration without assuming a particular curve shape. It learns a monotone step function that maps a model's scores to probabilities. This chapter covers how it works, how to apply it without leaking data, and where it fails.
This chapter assumes you can train a scikit-learn classifier and split data into train, validation and test sets. It also assumes you have read the chapters on reliability diagrams, Brier score and Platt scaling.
The idea
A calibrator is a function g that takes a model's score s and returns a corrected probability g(s). Platt scaling restricts g to a sigmoid with two parameters. Isotonic regression drops that restriction and keeps only one: g must never decrease as s increases.
That constraint makes sense. A higher score should never mean a lower chance of the positive class. Beyond that, the data decides the shape.
Formally, given scores s_1 ≤ s_2 ≤ ... ≤ s_n with labels y_i in {0, 1}, isotonic regression finds values g_1 ≤ g_2 ≤ ... ≤ g_n that minimize the squared error Σ (y_i − g_i)². This is the same quantity the Brier score measures.
The pool adjacent violators algorithm
The standard solver is the pool adjacent violators algorithm (PAV). It works like this:
- Sort the samples by score.
- Start with each sample as its own block, whose value is its label.
- Scan left to right. If a block's value is higher than the next block's value, the two violate monotonicity. Merge them into one block whose value is the average of its labels.
- After a merge, check backwards. The merged block may now violate the block before it, so keep merging until the values are non-decreasing.
Here is a small example. Eight scores come with these labels, which are not monotone:
from sklearn.isotonic import IsotonicRegression
scores = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8]
labels = [0, 0, 1, 0, 1, 0, 1, 1]
iso = IsotonicRegression(y_min=0.0, y_max=1.0, out_of_bounds="clip")
iso.fit(scores, labels)
print(iso.predict(scores))The output is [0. 0. 0.5 0.5 0.5 0.5 1. 1.]. The labels at scores 0.3 and 0.4 are 1, 0, so they merge into a block with value 0.5. The labels at 0.5 and 0.6 are 1, 0, so they merge the same way. The result is a staircase with three levels, which are 0, 0.5 and 1.
PAV is fast. After sorting, it runs in linear time.
Calibrating a real model
The calibrator must be fit on data the base model did not train on. A model's scores on its own training data are overconfident, so a calibrator fit on them learns the wrong correction. The simplest honest layout is three splits: one to train the model, one to fit the calibrator, and one to evaluate the result.
import numpy as np
from sklearn.calibration import calibration_curve
from sklearn.datasets import make_classification
from sklearn.isotonic import IsotonicRegression
from sklearn.metrics import brier_score_loss
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
X, y = make_classification(
n_samples=20000, n_features=20, n_informative=5, n_redundant=10, random_state=0
)
X_train, X_rest, y_train, y_rest = train_test_split(
X, y, test_size=0.5, random_state=0
)
X_cal, X_test, y_cal, y_test = train_test_split(
X_rest, y_rest, test_size=0.5, random_state=0
)
model = GaussianNB().fit(X_train, y_train)
p_cal = model.predict_proba(X_cal)[:, 1]
p_test = model.predict_proba(X_test)[:, 1]
iso = IsotonicRegression(y_min=0.0, y_max=1.0, out_of_bounds="clip")
iso.fit(p_cal, y_cal)
p_test_iso = iso.predict(p_test)
print("raw Brier :", brier_score_loss(y_test, p_test))
print("isotonic Brier:", brier_score_loss(y_test, p_test_iso))
print("distinct output levels:", len(np.unique(p_test_iso)))
frac_pos, mean_pred = calibration_curve(
y_test, p_test_iso, n_bins=10, strategy="quantile"
)
for m, f in zip(mean_pred, frac_pos):
print(f"mean predicted {m:.2f} -> observed fraction positive {f:.2f}")Naive Bayes is a good test case because it is known to push probabilities toward 0 and 1. The isotonic Brier score should be lower than the raw one, and the reliability table should sit close to the diagonal. Exact values depend on your scikit-learn version, so compare the two scores rather than expecting specific numbers.
Note that fit receives the scores first and the labels second. This is the reverse of a typical estimator call, because IsotonicRegression takes a single one-dimensional input. Pass a 1-D array, not a column matrix.
Parameters that matter
| Parameter | Meaning | Recommendation for calibration |
|---|---|---|
| `y_min`, `y_max` | Bounds on the output | Set to 0 and 1 so outputs are valid probabilities |
| `out_of_bounds` | Behaviour for scores outside the fitted range | Use `"clip"`. The default `"nan"` returns NaN |
| `increasing` | Direction of the constraint | Leave `True`. `"auto"` picks a direction from the data and can hide a bug |
The out_of_bounds setting matters more than it looks. The calibrator only knows the range of scores it saw during fitting. If the calibration set has a maximum score of 0.97, a test score of 0.99 is out of range. With the default setting you get NaN, and a downstream pipeline may silently drop or mishandle it.
Strengths
Isotonic regression is nonparametric, so it can fix distortions that a sigmoid cannot. A sigmoid can only stretch or shift one S-shaped curve. If a model is overconfident in the middle of its range and underconfident at the edges, a sigmoid cannot represent that, but a staircase can. This is why isotonic often wins on models such as boosted trees or naive Bayes, where the distortion is not a clean sigmoid.
It also needs no assumption about how the scores were produced. It works on any monotone relationship between score and true probability.
Weaknesses and failure modes
Overfitting on small calibration sets
Each step in the staircase is estimated from the samples in its block. With few samples, blocks are small and their averages are noisy. A rule of thumb is that isotonic starts to be reliable at roughly a thousand or more calibration samples. Below that, Platt scaling is usually safer because it has only two parameters. This is the main decision criterion covered in the chapter on choosing a method.
Rare positives make this worse. With 2% positives and 1,000 samples you have only about 20 positive labels. The block values are then built from very little information.
Ties and lost resolution
The output is a step function, so many different input scores map to the same probability. Two samples that the base model ranked differently can end up tied. That can lower AUC slightly, and it reduces the usefulness of the probabilities for ranking. Calibration improves one property at the cost of some resolution. If you need fine-grained ranking, keep the raw score for sorting and use the calibrated value only where the probability itself matters.
Edges and extrapolation
At the extremes, a block can average to exactly 0 or exactly 1 when only a few samples fall there. A predicted probability of exactly 0 is dangerous for any metric that takes a logarithm. Log loss would be infinite on a single wrong prediction. Clip outputs to a small interval, such as [1e-6, 1 - 1e-6], before computing log loss or using the probabilities in a downstream model.
Binary by construction
IsotonicRegression handles one score at a time, so it is naturally binary. For multiclass problems, scikit-learn fits one calibrator per class in a one-vs-rest fashion and then renormalizes. The multiclass chapter covers the consequences of that.
Using it through `CalibratedClassifierCV`
You rarely need to manage the splits by hand. CalibratedClassifierCV(estimator, method="isotonic", cv=5) trains the base model on each training fold, collects held-out scores from the other fold, and fits the isotonic calibrator on those pooled scores. The next chapter walks through this in detail, including how the final predictions are averaged across folds.
The manual version in this chapter is still worth knowing. It makes the data flow explicit, and you can inspect iso.X_thresholds_ and iso.y_thresholds_ to see exactly where the steps are.
Exercise
You have a gradient boosting model and only 300 labelled examples held out for calibration, 30 of them positive. A colleague suggests isotonic regression because it is more flexible than Platt scaling. What do you recommend, and why? Name one setting you would use if you do use isotonic.
Show answer
Prefer Platt scaling. Isotonic regression estimates a separate value for each block of samples, and with 30 positives those blocks are small and noisy, so the calibrator is likely to overfit. Platt scaling fits only two parameters and is more stable at this size. If you do use isotonic, set out_of_bounds="clip" (and y_min=0.0, y_max=1.0) so unseen scores do not produce NaN. You could also gather more calibration data, or use cross-validated calibration to reuse more of the data.
Exercise
Apply the pool adjacent violators algorithm by hand to the labels 1, 0, 0, 1 (already sorted by score). What are the fitted values?
Show answer
Start with blocks 1, 0, 0, 1. The first block (1) exceeds its right neighbour (0), so merge them into a block of value 0.5 covering two samples. The next block is 0, and 0.5 exceeds 0, so merge again into a block of three samples with value 1/3. The last block is 1, which is not below 1/3, so it stays. The fitted values are 1/3, 1/3, 1/3, 1.