Sub topic 9
Platt scaling
This chapter assumes you know logistic regression, the sigmoid function, and how to split data into train, validation and test sets. It also assumes you have read the earlier chapters on reliability diagrams and on fitting a calibrator without leaking data. Here you will learn what Platt scaling is, how to fit it by hand, and where it fails.
The idea
Platt scaling is a post-hoc calibration method. It takes a classifier that outputs a real-valued score f and fits a small logistic regression that maps that score to a probability. The classifier is not retrained.
John Platt introduced it in 2000 to turn support vector machine margins into probabilities. The mapping is:
P(y = 1 | f) = 1 / (1 + exp(A * f + B))A and B are the only two parameters. Platt's sign convention puts a minus on the score, so a good model has a negative A. Scikit-learn's LogisticRegression uses 1 / (1 + exp(-(w * f + b))). The two forms match when A = -w and B = -b.
The two parameters do different jobs:
Astretches or compresses the scores. A large slope makes probabilities more extreme. A small slope pulls them toward the middle.Bshifts the whole curve. It moves the score at which the predicted probability crosses 0.5.
When the sigmoid is the right shape
Platt scaling assumes the distortion in the scores is itself sigmoid-shaped. That is a good fit for several common models:
| Base model | Typical miscalibration | Does Platt scaling suit it? |
|---|---|---|
| Linear SVM | Margins are not probabilities at all | Yes. This was the original use case. |
| Boosted trees, AdaBoost | Probabilities pushed away from 0 and 1 | Usually yes. The reliability curve looks like a sigmoid. |
| Naive Bayes | Probabilities pushed toward 0 and 1 | Often partly. A sigmoid can shrink them, but the shape may be wrong. |
| Random forest | Probabilities pulled toward the middle | Sometimes. Isotonic regression often does better with enough data. |
If the reliability diagram shows a clearly non-sigmoid shape, such as a plateau followed by a jump, two parameters cannot fix it. That is where isotonic regression is the better choice, and a later chapter covers it.
Fitting it by hand
The code below trains a linear SVM on one part of the data, fits the Platt sigmoid on a second part, and evaluates on a third. The three-way split is the leakage rule from the previous chapter in practice. The calibrator must never see the examples the SVM was trained on, because training scores are over-confident.
import numpy as np
from scipy.special import expit
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import brier_score_loss, log_loss, roc_auc_score
from sklearn.model_selection import train_test_split
from sklearn.svm import LinearSVC
X, y = make_classification(
n_samples=30000, 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
)
svm = LinearSVC(dual=False, random_state=0).fit(X_train, y_train)
s_cal = svm.decision_function(X_cal).reshape(-1, 1)
s_test = svm.decision_function(X_test)
# Platt scaling: a nearly unregularized logistic regression on the 1-D score.
platt = LogisticRegression(C=1e6).fit(s_cal, y_cal)
p_platt = platt.predict_proba(s_test.reshape(-1, 1))[:, 1]
# Baseline: push the raw margin through a sigmoid without fitting anything.
p_naive = expit(s_test)
print("slope w:", platt.coef_[0, 0], " intercept b:", platt.intercept_[0])
print("AUC raw score:", roc_auc_score(y_test, s_test))
print("AUC Platt :", roc_auc_score(y_test, p_platt))
print("Brier naive :", brier_score_loss(y_test, p_naive))
print("Brier Platt :", brier_score_loss(y_test, p_platt))
print("LogLoss naive :", log_loss(y_test, p_naive))
print("LogLoss Platt :", log_loss(y_test, p_platt))Check three things in the output:
- The AUC values are identical, because the fitted sigmoid is monotonic and does not change the ranking.
- The Brier score and log loss for the fitted sigmoid should be lower than for the naive sigmoid. The exact numbers depend on your library versions.
- The slope
wshows how far the raw margins were from being probabilities. A value far from 1 means the naive sigmoid was badly scaled.
Setting C=1e6 turns off almost all regularization. Platt scaling has only two parameters, so the default penalty only adds bias.
Platt's target smoothing
Platt's original paper does not fit against the raw 0/1 labels. It uses smoothed targets computed from the class counts N+ and N- in the calibration set:
t+ = (N+ + 1) / (N+ + 2)
t- = 1 / (N- + 2)Positives get a target just below 1, and negatives get one just above 0. The smoothing comes from a Bayesian argument with a uniform prior on the outcome at each score. It matters most when the calibration set is small or when the scores separate the classes almost perfectly. In that case, an unsmoothed fit can push A toward infinity.
Scikit-learn's method="sigmoid" applies this smoothing. The hand-fitted LogisticRegression above does not, so the two can differ slightly on small calibration sets.
Platt scaling in scikit-learn
You rarely need to do the split yourself. CalibratedClassifierCV handles it with cross-validation:
from sklearn.calibration import CalibratedClassifierCV
from sklearn.svm import LinearSVC
calibrated = CalibratedClassifierCV(
LinearSVC(dual=False, random_state=0), method="sigmoid", cv=5
)
calibrated.fit(X_train, y_train)
p_cv = calibrated.predict_proba(X_test)[:, 1]
print("Brier CV Platt:", brier_score_loss(y_test, p_cv))With cv=5 and the default ensemble=True, the wrapper does the following:
- It splits the training data into 5 folds.
- For each fold, it trains a clone of the base model on the other 4 folds and fits a sigmoid on the held-out fold's scores.
- At prediction time, it averages the probabilities of the 5 calibrated models.
Every calibration score therefore comes from a model that did not see that example. LinearSVC has no predict_proba, so the wrapper uses its decision_function.
The diagram shows where each piece of data goes in the manual version.
Gotchas and failure modes
- Calibrating on training data. Scores on training examples are more extreme than scores on new data. A sigmoid fitted on them under-corrects and leaves the model over-confident.
- Too few calibration examples. Two parameters need far less data than isotonic regression, but a few hundred examples can still give noisy estimates. Few positives are the real bottleneck.
- Non-sigmoid distortion. If the reliability curve bends in a way a sigmoid cannot follow, Platt scaling can improve one region and worsen another. Always re-draw the reliability diagram on held-out data after calibrating.
- Accuracy can change. The sigmoid keeps the ranking, but the 0.5 probability threshold may now correspond to a different score cut-off than the original one. Predicted labels at 0.5 can therefore change, especially when
Bis far from zero. - Class imbalance. The intercept learns the base rate in the calibration set. If deployment data has a different base rate, the calibrated probabilities will be off, a problem the distribution shift chapter covers.
Exercise
A linear SVM scores 0.8 AUC on your test set. You fit a Platt sigmoid on a separate calibration split and recompute AUC on the test set. What do you expect to happen to the AUC, and why? Also name one metric that should improve.
Show answer
The AUC stays the same. A Platt sigmoid is a monotonic function of the score, so it never changes the order of the examples, and AUC depends only on that order. Brier score and log loss should improve, because they measure how close the probabilities are to the observed outcomes, and the sigmoid corrects the scale and offset of the scores.
Exercise
Why does the hand-fitted example use C=1e6 in LogisticRegression, and why must the SVM be trained on a different split from the one used to fit the sigmoid?
Show answer
Platt scaling has only two parameters, so regularization adds bias and little protection against overfitting. A very large C makes the penalty negligible. The SVM must not be trained on the calibration split because its scores on its own training examples are more extreme than on new data. A sigmoid fitted to those scores would learn the wrong scale and leave the model over-confident on unseen data.