Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 3: Classical Machine LearningCore Concepts

Calibration and class imbalance

P3.A1040 min●●○ IntermediateReviewed Dec 2, 2026

Why this matters for machine learning

A classifier's number is only useful as a probability if “0.9” really means “right about 90% of the time”. Calibration measures and repairs that, and rare classes need their own care because they break both the meaning of the number and the default 0.5 threshold.

  • A decision threshold chosen from the cost of a miss and the cost of a false alarm is only the right one when the probabilities are calibrated. (P3.A9: Evaluation metrics)
  • Deep networks are often more confident than they are right, and regularization choices such as weight decay and label smoothing change how confident they are. (P4.17: Regularization for neural nets)
  • Fraud, equipment faults and rare diseases have very few positive cases, so accuracy hides the problem and resampling or class weights change the probabilities a model reports. (P3.C5: Anomaly detection)
  • Fairness checks include asking whether the same score means the same thing for different groups of people, which is calibration within each group. (P12.7: Fairness, coming soon)

Before this: Logistic regression, Evaluation metrics

After this lesson you can

  • Define calibration, build a reliability diagram from predictions and outcomes, and read over-confidence and under-confidence from it
  • Compute the expected calibration error, the Brier score and the log loss, and explain why the last two are proper scoring rules and accuracy is not
  • Explain with numbers why calibration, accuracy and ranking are different properties, and repair calibration with Platt, temperature or isotonic calibration fitted on held-out data
  • Say what class imbalance changes and what it does not, choose a threshold from costs, use class weights and resampling, and correct probabilities for the shifted class prior

In P2.8 a sentiment model was given a sentence with no sentiment at all, “The meeting is at 3 pm.”, and still answered with a score of 0.929. The score looked like confidence. It was not a measure of being right: the model must give some label, and 0.929 only says how strongly it prefers that label to the other. That raises the question this lesson answers. When a model says 0.9, what should 0.9 mean, how can you test it, and what can you do when it is wrong?

The second half is about a closely related trouble. When one class is rare, a model can look excellent and still be useless, the usual threshold of 0.5 stops making sense, and the common fixes (class weights, resampling) quietly change the numbers the model reports. The two halves belong together because both are about what a predicted probability means.

What “90%” should mean

A weather forecaster says “70% chance of rain” on many days. You cannot check one day: it rains or it does not. But you can collect all the days with a 70% forecast and count. If it rained on about 70 of 100 such days, the forecaster is calibrated at 70%. If it rained on 40 of them, the forecaster is over-confident: the forecasts were farther from 50% than the weather was.

For a classifier that reports a probability p^\hat p that the case is positive (y=1y=1), calibrated means

P(y=1∣p^=p)=pfor every value p.\begin{aligned} \mathbb{P}(y=1\mid\hat p=p)&=p\\ &\text{for every value }p. \end{aligned}

Read it as: among the cases where the model says pp, the share that are positive is pp. It is a statement about a group of cases with the same prediction, not about one case. A single outcome never confirms or refutes “0.9”. And a real-valued p^\hat p is almost never repeated exactly, so in practice we group predictions that are close together. That grouping is the reliability diagram.

A reliability diagram by hand

Here is a tiny, made-up example. A spam filter looked at 30 emails and said 0.9 for ten of them, 0.5 for ten and 0.2 for ten. Afterwards we learn which were really spam:

  • said 0.9: 6 of the 10 were spam, a share of 0.60 (a gap of 0.30 from what it said)
  • said 0.5: 5 of the 10 were spam, a share of 0.50 (no gap)
  • said 0.2: 3 of the 10 were spam, a share of 0.30 (a gap of 0.10)

Plot one point per group: said (horizontal) against observed share (vertical). The points are (0.9,0.6)(0.9,0.6), (0.5,0.5)(0.5,0.5) and (0.2,0.3)(0.2,0.3). A calibrated model puts them on the diagonal. The first point is well below it, and the last is above it. Both mean the same thing: the filter’s numbers are farther from 0.5 than the real shares are. It is over-confident.

With real scores no two cases are equal, so we make the groups by binning. The recipe:

  1. Collect the predictions p^i\hat p_i and outcomes yi∈{0,1}y_i\in\{0,1\} on data the model was not trained on (P3.A4). On its own training data an overfit model looks better than it is.
  2. Cut [0,1][0,1] into BB bins of equal width. Bin bb (counting from 0) holds the cases with b/B≤p^<(b+1)/Bb/B\le\hat p<(b+1)/B, and the last bin also holds p^=1\hat p=1.
  3. For each bin that has cases, compute the count nbn_b, the mean prediction pˉb\bar p_b and the share of positives yˉb\bar y_b.
  4. Plot (pˉb,yˉb)(\bar p_b,\bar y_b) together with the diagonal, and show nbn_b (by dot size or a bar chart). A dot made from three cases tells you much less than one made from three hundred.

The number of bins BB is a choice, and it matters, as the widget shows next.

Try the reliability diagram

The data in the widget are made up. Each of 1,000 test cases has a hidden true probability of being positive, and its outcome was drawn with that probability. An honest model reports the true probability. The other models report it after multiplying its log-odds (the logit, P3.A7) by a number kk: k>1k>1 makes every prediction more extreme, k<1k<1 less extreme. A second set of 1,000 cases, the calibration set, is kept apart for fitting the fixes you meet below. The data come from a seeded generator, so the numbers quoted here match the starting sample.

Fix:
000.250.250.50.50.750.7511mean predicted probability in the binshare positivecases58

● bin: mean prediction against share positive (bigger dot = more cases), | gap to the diagonal, - - perfect calibration. Bars below: cases per bin (tallest 405). Tap a dot or bar to inspect a bin.

Bin 9 of 10 (0.80 to 0.90): 58 cases, mean prediction 0.85, 36 positive (0.62), gap 0.23.

ECE: 0.140
Brier score: 0.188
log loss: 0.652
AUC: 0.832

Over-confident: the dots lie below the diagonal on the right and above it on the left. Predictions are farther from 0.5 than the outcomes are.

Reliability diagram on made-up data. Each blue dot is one bin: horizontal position is the mean prediction in the bin, vertical position is the share of positive cases, and the dot area grows with the number of cases. The red segment is the gap to the diagonal (perfect calibration). The bars underneath show the cases per bin on the same axis. Choose a model, change the number of bins, and try a fix fitted on the calibration set. ECE, Brier score, log loss and AUC are measured on the test cases. Tap a dot or a bar, or use the Inspect bin slider, to read one bin.

Things to try, in order:

  1. Start with Well calibrated. The dots lie near the diagonal but not exactly on it: with 10 bins the ECE is 0.038, and this is chance, not miscalibration (the lesson comes back to this).
  2. Switch to Over-confident. The dots form a flat S: below the diagonal on the right, above it on the left. The bars show why: 405 of the 1,000 predictions are in the lowest bin, where the model says about 0.02 and the share positive is 0.15, and 217 are in the highest bin, where it says 0.98 and the share is 0.84. The ECE is 0.140.
  3. Switch to Under-confident. Now the S is steep: above the diagonal on the right, below on the left. The model keeps its predictions near the middle, but the outcomes are more decided than that. The ECE is 0.099. Only 5 and 3 cases fall in the two outer bins, so those dots are shaky.
  4. Go back to Well calibrated and slide the number of bins. The ECE is 0.016 with 5 bins, 0.038 with 10 and 0.050 with 20, for the same honest model. Few bins average away real gaps; many bins fill with few cases and pick up noise.
  5. Choose Over-confident again and press Temperature, then Platt. The dots snap onto the diagonal and the ECE falls to 0.038 and 0.053. The AUC stays at 0.832 in every case. Why the ranking does not move is explained below.
  6. Choose Base rate only. Every case gets the same number, so there is one dot, and it sits near the diagonal.

Three numbers for calibration

A diagram is a picture. To compare models, or to watch calibration change, you want numbers. There are three common ones.

Expected calibration error (ECE). It summarizes the gaps in the bins. With the equal-width bins above, NN cases in all and nbn_b in bin bb:

ECE=∑bnbN ∣yˉb−pˉb∣,\mathrm{ECE}=\sum_{b}\frac{n_b}{N}\,\bigl|\bar y_b-\bar p_b\bigr| ,

the average gap between the observed share and the mean prediction, each bin weighted by its share of the cases. For the 30 emails every bin holds one prediction value, so ECE=13(0.30+0.00+0.10)=0.1333\mathrm{ECE}=\tfrac13(0.30+0.00+0.10)=0.1333. This lesson uses the probability of the positive class. For models with more than two classes, a common version uses the model’s confidence in its top class instead (see the Go deeper box in the next section). The ECE depends on the number and placement of the bins, and it has the noise problem described below.

The Brier score. It is the mean squared error of the probabilities against the 0/1 outcomes (P3.A2):

Brier=1N∑i=1N(p^i−yi)2.\mathrm{Brier}=\frac1N\sum_{i=1}^{N}(\hat p_i-y_i)^2 .

It needs no bins. A model that always says 0.5 scores 0.25, and a model that is always sure and right scores 0. For the 30 emails: the ten cases at 0.9 give 6(0.1)2+4(0.9)2=3.306(0.1)^2+4(0.9)^2=3.30, the ten at 0.5 give 10(0.5)2=2.5010(0.5)^2=2.50, and the ten at 0.2 give 3(0.8)2+7(0.2)2=2.203(0.8)^2+7(0.2)^2=2.20. The total is 8.00, so the Brier score is 8/30=0.26678/30=0.2667. The score was introduced for weather forecasts in 1950 (by Glenn Brier).

Log loss. It is the binary cross-entropy of P1.E3 and P3.A7, the loss that logistic regression and most neural classifiers are trained with:

log loss=1N∑i=1Nℓi,ℓi=−yiln⁡p^i−(1−yi)ln⁡(1−p^i).\begin{aligned} \text{log loss}&=\frac1N\sum_{i=1}^{N}\ell_i,\\ \ell_i&=-y_i\ln\hat p_i\\ &\quad-(1-y_i)\ln(1-\hat p_i). \end{aligned}

For the 30 emails it is 0.7721 nats (a nat is the unit when the logarithm is natural).

Go deeper Confident mistakes: log loss against Brier

Log loss and Brier punish confident mistakes differently. A model that says 0.99 and is wrong pays −ln⁡0.01=4.605-\ln 0.01=4.605 nats of log loss, which has no upper limit as the prediction approaches 1, but only 0.992=0.9800.99^2=0.980 of Brier, which cannot exceed 1.

Why Brier and log loss are the right scores: they are proper

A score is called proper if a model that knows the true probability does best, on average, by reporting exactly that probability. This is what we want from a score: it cannot be gamed by saying something other than what you believe.

Suppose a case is spam with true probability q=0.8q=0.8, and you report rr. The expected values below come from P1.E3’s calculation for log loss and the same calculation for the others (the cell in Try it prints them):

report rrlog lossBrierabs. error
0.50.6930.2500.500
0.70.5260.1700.380
0.80.5000.1600.320
0.90.5450.1700.260
0.990.9290.1960.206

Each column is the expected score of one rule (abs. error is ∣r−y∣\lvert r-y\rvert).

Log loss and Brier are lowest at r=0.8r=0.8. The absolute error ∣r−y∣|r-y| is not proper: it is lowest at r=0.99r=0.99 and would reward a model that exaggerates (the expected value is 0.8−0.6r0.8-0.6r, which keeps falling until r=1r=1). Accuracy is also not proper: any rr above 0.5 gives the same accuracy, so accuracy cannot tell an honest 0.8 from an inflated 0.99. That is why we measure probabilities with Brier or log loss, and use accuracy only for labels.

Go deeper Splitting the Brier score into three parts

When the predictions take a few distinct values, with nvn_v cases having prediction vv, share yˉv\bar y_v positive, and base rate yˉ\bar y overall, the Brier score splits exactly into three terms:

Brier=R−D+U,R=∑vnvN(v−yˉv)2,D=∑vnvN(yˉv−yˉ)2,U=yˉ(1−yˉ).\begin{aligned} \mathrm{Brier}&=R-D+U,\\ R&=\sum_v \tfrac{n_v}{N}(v-\bar y_v)^2,\\ D&=\sum_v \tfrac{n_v}{N}(\bar y_v-\bar y)^2,\\ U&=\bar y(1-\bar y). \end{aligned}

Reliability RR is the squared version of the calibration gap (smaller is better). Resolution DD measures how far the groups’ outcome shares are from the overall base rate, that is, how much the predictions separate the cases into different groups (larger is better). Uncertainty UU is the Brier score of always saying the base rate, and nothing about the model changes it. For the 30 emails, with base rate 14/3014/30: 0.0333−0.0156+0.2489=0.26670.0333-0.0156+0.2489=0.2667. So the Brier score rewards honesty and the ability to tell cases apart in one number. For continuous predictions that are binned, the identity is only approximate.

Over-confident, under-confident, and noise

The two ways to be wrong have two shapes on the diagram:

  • Over-confident: predictions are farther from 0.5 than the outcomes. The curve is flatter than the diagonal: below it on the right, above it on the left.
  • Under-confident: predictions are too timid. The curve is steeper than the diagonal.

Which one is common? That depends on the model, but there is a clear case. In 2017, Chuan Guo and co-authors (“On Calibration of Modern Neural Networks”, ICML 2017) reported that modern deep networks were poorly calibrated compared with networks from about a decade earlier, and that depth, width, weight decay and batch normalization all affect it. This is a pattern, not a law: a model trained on plenty of data with the right model family can be well calibrated, which is the promise P1.E3 made about cross-entropy.

A diagram needs two cautions before you read gaps from it.

Even an honest model has a nonzero ECE. Each bin holds a limited number of cases, and the observed share is a random average. In a simulation of 500 samples of 1,000 cases from an honest model, the ECE averaged 0.023 with 5 bins, 0.031 with 10 and 0.044 with 20, and 90% of the samples fell within 0.011 to 0.036, 0.020 to 0.044 and 0.032 to 0.056. So an ECE of 0.03 to 0.04 on 1,000 cases and 10 bins is what an honest model gives, and the ECE grows with the number of bins for an honest model. Compare ECE values only when the number of cases and bins are the same.

Bins with few cases are unreliable. That is why the diagram must show the counts, and why a lone dot made of 3 cases should not worry you.

Go deeper Why networks drift toward over-confidence

Once a training case is classified correctly, making its logit larger still lowers its cross-entropy, so training keeps pushing the logits up unless something holds them back (weight decay, early stopping, P4.17). This is one easy-to-see mechanism, not the whole story.

Go deeper More than two classes

For a multi-class model with softmax outputs (P3.A8), the usual version looks at the top label: for each case take the largest probability (the model’s confidence) and whether the predicted class was right. Bin by the confidence, compare the mean confidence in each bin with the accuracy in it, and average the gaps with the same weights as above. This is the ECE of Guo et al., who used 15 bins and the top-label confidence (this lesson uses 10 bins and the probability of the positive class). It checks only the top probability. A stricter idea, classwise calibration, checks each class’s probability on its own. Both versions need enough cases per bin, and with many classes the top-label confidences crowd near 1, so the highest bins get most of the cases.

Calibration is not accuracy, and not ranking

Three different questions can be asked about a classifier that outputs probabilities:

  • Accuracy: is the label right (when you cut at a threshold)?
  • Ranking (discrimination): do the positive cases get higher scores than the negative ones? The area under the ROC curve (AUC) measures it (P3.A9).
  • Calibration: do the numbers mean what they say?

They can disagree. Here are three demonstrations with numbers.

The same ranking with very different calibration. In the widget the three models differ only in the multiplier kk, and the AUC is 0.832 for all of them, while their ECE values are 0.038, 0.140 and 0.099. Multiplying every logit by the same positive number never changes which case scores higher than which, so the ranking is untouched and the calibration is not.

Perfect ranking, wrong probabilities. Take 100 negative cases that the model scores 0.3 and 100 positive cases that it scores 0.7. Every positive scores above every negative, so the AUC is 1, and a threshold of 0.5 gives 100% accuracy. But the bin at 0.3 holds no positives and the bin at 0.7 holds only positives, so the ECE is 0.3, the Brier score is 0.09 and the log loss is 0.357. A model that said 0 and 1 would have scored 0 on both. The ranking is right and the numbers are timid.

Calibrated and useless. Say the base rate for every case. In the widget’s Base rate only model, with a base rate of 0.438 estimated on the calibration set, the ECE is 0.018 (the base rates of the two sets differ a little by chance), yet the AUC is 0.5, the Brier score is 0.244 and the log loss is 0.681. The honest model has 0.165 and 0.493. A forecast can be calibrated and still carry no information.

Fixing calibration

The ranking of an over-confident model may be fine and only the numbers are off. Then a small post-processing step can repair the numbers, with no change to the model itself. One rule matters most: fit the fix on a calibration set that the model has not been trained on and that is not the test set (P3.A4). On the training data the model already looks well calibrated, and fitting on the test set would make the final report optimistic.

All three methods learn a function from the model’s score to a probability.

Platt scaling. Take the model’s raw score ss (the logit, or the output of a margin-based model such as a support vector machine, P3.B6) and fit a logistic regression with one input on the calibration set:

p^new=σ(a s+b).\hat p_{\text{new}}=\sigma(a\,s+b).

Two numbers: aa stretches or squeezes the score, bb shifts it. They are fitted by minimizing log loss (P3.A7). The method is named for John Platt, who proposed it in 1999 for the outputs of support vector machines. In the widget the over-confident model’s fit is a=0.41a=0.41 and b=0.16b=0.16: it squeezes the logits by a factor of about 1/0.41≈2.41/0.41\approx2.4 (the true factor is 2.5) and adds a small shift (the calibration set has a slightly higher share of positives, 0.438, than the test set, 0.420, the fit also has sampling noise).

Temperature scaling. The special case b=0b=0 with a=1/Ta=1/T, so there is one number, the temperature T>0T>0:

p^new=σ(s/T).\hat p_{\text{new}}=\sigma(s/T).

For several classes the same idea is softmax(z/T)\mathrm{softmax}(\mathbf{z}/T).

T>1T>1 pulls probabilities toward the middle (it fixes over-confidence), T<1T<1 pushes them outward. For the logits (4,1,0)(4,1,0) of a three-class model, softmax (P3.A8) gives (0.936,0.047,0.017)(0.936,0.047,0.017) at T=1T=1, (0.736,0.164,0.100)(0.736,0.164,0.100) at T=2T=2 and (0.543,0.257,0.200)(0.543,0.257,0.200) at T=4T=4. TT is chosen to minimize the log loss on the calibration set. Dividing by a positive number never changes which logit is largest, so the predicted class and the accuracy do not change, only the confidence. Guo et al. found this one-parameter fix to work well on most of the data sets they tried. The over-confident widget model needs T=2.51T=2.51, close to its true factor of 2.5. (The same division of logits by a temperature appears in text generation, P10.A5, where its purpose is different: to make sampling more or less random.)

Isotonic regression. It fits a non-decreasing step function from the score to the probability. It is the most flexible of the three and needs a larger calibration set (details in the Go deeper box below).

Go deeper Isotonic regression in more detail

Fit a non-decreasing step function from the score to the probability. It adds no assumption about the S shape of the correction, so it can fix curves that Platt cannot, but it has as many free steps as the data allow and tends to overfit when the calibration set is small. The scikit-learn documentation says it is not recommended when the number of calibration samples is much smaller than 1,000. Platt and temperature scaling have two and one parameters and are safer on small sets.

On the widget’s over-confident model, fitted on the calibration set and measured on the test set, temperature scaling takes the ECE from 0.140 to 0.038, the Brier score from 0.188 to 0.165 and the log loss from 0.652 to 0.492. Platt scaling gives 0.053, 0.166 and 0.496. Both are about as good as the honest model (0.038, 0.165, 0.493), and the difference between them is chance.

What these fixes cannot do:

  • They keep the ranking. The fitted function is increasing, so the AUC is unchanged (0.832 above). A weak model stays weak.
  • They are fitted for one situation. A calibration step learned on one population can break when the data change, for instance when the share of positives changes. That is the subject of the second half of this lesson.
  • They need honest held-out data. A calibration set that is small gives a noisy fit, which is one more reason for the simple one- and two-parameter methods.

When one class is rare

Class imbalance means the classes are far from equally common. P1.D12 gave the standard example: 950 examples of class A and 50 of class B. A classifier that says “A” for everything is right 95% of the time and finds none of the B cases. Fraud, faults and many diseases are like this, and the rare class is usually the one that matters. P3.A9 explains how precision, recall and the PR curve see through the accuracy trap; this lesson does not repeat it.

What imbalance changes, and what it leaves alone:

  • The baseline. High accuracy comes for free, so accuracy alone says little.
  • The threshold. A calibrated model rarely says 0.5 or higher about a rare class. Cutting at 0.5 then labels almost everything negative.
  • Probabilities after resampling or weighting. These tools make the rare class look more common to the training procedure, and the model’s probabilities then overstate the real rate (shown below).
  • How well the rare class is measured. With few positives, recall and the top bins of the reliability diagram rest on few cases and are noisy.
  • What stays the same: the meaning of a probability (calibration is still the test), and the ranking ability of a model. The AUC compares positive cases with negative cases pair by pair, so it does not depend on how many of each there are (P3.A9).

A worked example

The data are made up, and the cell in Try it reruns every number. There is one feature. Negative cases have a feature that is normal with mean 0 and spread 1, and positive cases have mean 1.5 and spread 1. About 5% of the cases are positive. The training set has 20,000 cases, of which 991 are positive. A large test set of 200,000 cases (base rate 0.0498) is used to measure. The model is logistic regression (P3.A7) fitted four ways:

  • plain, with every case counted once
  • weights, with the balanced class weights described below
  • undersample, with the 991 positives and 991 random negatives
  • oversample, with all the negatives and 19,009 positives drawn with repetition

The result:

modelmeanrecallECE
plain0.0490.0920.003
weights0.3350.7800.285
under0.3310.7750.281
over0.3370.7820.287

(“mean” is the mean predicted probability, recall is at the threshold 0.5, and under and over are undersample and oversample. After the correction below, the ECE is 0.003 for all four.)

The plain model’s probabilities are honest: they average 0.049, close to the true 0.050, and the ECE is 0.003. (For unregularized logistic regression with an intercept this is expected: the fit makes the mean prediction on the training data equal the training base rate.) But at the threshold 0.5 it finds only 9.2% of the positives (this share is the recall, P3.A9), while its accuracy of 0.952 is barely above the 0.950 of saying “negative” every time.

The three methods that rebalance the classes find about 78% of the positives at 0.5. The price is in the probabilities: they average 0.33 when the true rate is 0.05, and the ECE jumps to 0.28 or more. The prior-shift correction below repairs this.

Choosing the threshold from costs

If a missed positive costs cFNc_{\text{FN}} and a false alarm costs cFPc_{\text{FP}}, the best rule says “positive” when

p  ≥  cFPcFP+cFN.p\;\ge\;\frac{c_{\text{FP}}}{c_{\text{FP}}+c_{\text{FN}}} .

This holds when pp is a calibrated probability and correct decisions cost nothing (P3.A9 derives it). In the example a miss costs 10 and a false alarm costs 1, so the threshold is 1/11=0.0911/11=0.091. The average cost per 1,000 cases on the test set:

  • always say “negative”: 498.1
  • plain model, threshold 0.5: 454.7
  • plain model, threshold 0.091: 294.5
  • weighted model, threshold 0.5: 328.7
  • weighted model with its probabilities shifted back, threshold 0.091: 294.7

The weighted model at 0.5 does better than the plain model at 0.5 because its 0.5 corresponds to a threshold of 0.05 on the real probability.

Class weights

Class weights change the loss. The average loss of P3.A1 becomes a weighted average:

L=1N∑i=1Nwyi ℓ(p^i,yi),\mathcal{L}=\frac1N\sum_{i=1}^{N} w_{y_i}\,\ell(\hat p_i,y_i),

where ℓ\ell is the loss on one case and wyiw_{y_i} is the weight of that case’s class. A weight of 10 does exactly what repeating the case 10 times in the data would do to the loss, without storing the copies. The weights class_weight="balanced" in scikit-learn are

wc=NK Nc,w_c=\frac{N}{K\,N_c},

with NN cases, KK classes and NcN_c cases in class cc. In the example N=20,000N=20{,}000, K=2K=2, and the positives get 20000/(2⋅991)=10.0920000/(2\cdot991)=10.09 and the negatives 20000/(2⋅19009)=0.52620000/(2\cdot19009)=0.526. Each class now has the same total weight, as if the classes were 50/50.

Resampling

  • Undersampling throws away cases of the common class until the classes are about equal. It is fast and loses information.
  • Oversampling repeats cases of the rare class. No information is lost, but repeated cases make it easy to memorize them (P3.A3).
Go deeper SMOTE

SMOTE (Chawla and co-authors, 2002) makes new, synthetic rare-class cases by interpolating between a rare case and one of its nearest rare neighbours (P3.B1). Evidence on whether it beats class weights or a good threshold is mixed, so treat it as one more option to test, not a default. The imbalanced-learn library implements it.

Resample after splitting the data and only the training part. A validation or test set must keep the real class ratio, or the scores measure the wrong situation. If you oversample before splitting, copies of the same case land on both sides of the split, and the validation score is inflated (the leakage of P3.A11).

The prior-shift correction

Why do weights and resampling push the probabilities up? A classifier’s output is meant to be the posterior of P1.D6. In odds form, Bayes’ theorem says

p(y=1∣x)p(y=0∣x)⏟posterior odds=p(x∣y=1)p(x∣y=0)⏟likelihood ratio×π1−π⏟prior odds,\underbrace{\frac{p(y{=}1\mid\mathbf{x})}{p(y{=}0\mid\mathbf{x})}}_{\text{posterior odds}} =\underbrace{\frac{p(\mathbf{x}\mid y{=}1)}{p(\mathbf{x}\mid y{=}0)}}_{\text{likelihood ratio}} \times\underbrace{\frac{\pi}{1-\pi}}_{\text{prior odds}},

where π\pi is the share of positives. Weights and resampling change the prior π\pi the model learns from, to a new value π′\pi' (0.5 for “balanced”), and leave the likelihood ratio alone. So the model’s odds are off from the true odds by the ratio of the prior odds, and the fix is to multiply that ratio back:

true odds=model odds×π/(1−π)π′/(1−π′).\begin{aligned} \text{true odds}={}&\text{model odds}\\ &\times\frac{\pi/(1-\pi)}{\pi'/(1-\pi')} . \end{aligned}

In the example π=0.05\pi=0.05 and π′=0.5\pi'=0.5, so the odds are multiplied by 0.05/0.95=1/190.05/0.95=1/19. The ECE drops from 0.285 to 0.003. This is the same formula as the last Go-deeper box of P1.D6: a score of 0.9 (odds 9) from a model that saw 50% positives is 9×199=1119\times\frac1{99}=\frac1{11} (these are odds), a probability of 112≈8.3%\frac1{12}\approx8.3\% when the real rate is 1%. One more case with simple numbers:

  • Keeping one in ten negatives makes the positives look ten times as common, so the true odds are 0.1×0.1\times the model’s odds. A model value of 0.5 (odds 1) means odds 0.1, a probability of 1/11=0.0911/11=0.091.

The correction is exact only if the likelihoods are really unchanged and the model fits well (here it does, by construction). If the real data differ in other ways, it is an approximation. And if all you need is a ranking, or a threshold chosen on validation data with the real class ratio, you can skip the correction.

Stratified splits, and more data

With few rare cases a random split can go wrong. Take 1,000 cases with 20 positives and a random 20% test split of 200 cases. The test set should hold 4 positives on average, but chance can leave very few. A stratified split keeps the class shares in every part (exactly 4 here), and the same idea works inside cross-validation (P3.A4). It matters most when a class is rare.

Go deeper How badly can a random split go

The number of positives in the random test set follows a hypergeometric distribution: mean 4, spread about 1.8, a 1.1% chance of none and a 6.7% chance of at most one.

Often the strongest remedy is the plainest: collect more cases of the rare class. If you collect them on purpose, the share of positives changes, which is another prior shift, so correct the odds when you need honest probabilities.

Depth: three ways to see it

Intuition

A bathroom scale that reads 2 kg too high still puts people in the right order, from lightest to heaviest, but every number is wrong. A calibration step is like weighing a known 10 kg object on it, noticing the 2 kg error and subtracting it. For classifiers the reference is a set of cases whose outcomes you know, and the correction is the stretch and shift of Platt scaling. The analogy breaks in one place: a scale has one error to subtract, but a classifier can be over-confident in one range of scores and fine in another, so the correction is a curve fitted to data, not one number (and a scale that reads 10% too high would need a stretch instead of a shift, which is the other Platt parameter), and it needs enough cases to be fitted well.

Math

Calibration: P(y=1∣p^)=p^\mathbb{P}(y=1\mid\hat p)=\hat p. ECE with equal-width bins: ∑bnbN∣yˉb−pˉb∣\sum_b\frac{n_b}{N}\lvert\bar y_b-\bar p_b\rvert.

Proper scores for a case with true P(y=1)=q\mathbb{P}(y=1)=q and reported rr. Write B(r)B(r) for the expected squared error:

B(r)=q(1−r)2+(1−q)r2=(r−q)2+q(1−q).\begin{aligned} B(r)&=q(1-r)^2\\ &\quad+(1-q)r^2\\ &=(r-q)^2+q(1-q). \end{aligned}

For the log loss of one case, −yln⁡r−(1−y)ln⁡(1−r)-y\ln r-(1-y)\ln(1-r), the expected value is

H(q)+DKL(q ∥ r).H(q)+D_{\mathrm{KL}}(q\,\Vert\,r).

Both are minimized at r=qr=q: the first because of the square, the second by Gibbs’ inequality (P1.E4). The absolute error has E∣r−y∣=q(1−r)+(1−q)r=q+(1−2q)r\mathbb{E}\lvert r-y\rvert=q(1-r)+(1-q)r=q+(1-2q)r, which is linear in rr, so for q>12q>\tfrac12 it is smallest at r=1r=1, not at r=qr=q.

Cost threshold: say positive iff p cFN≥(1−p) cFPp\,c_{\text{FN}}\ge(1-p)\,c_{\text{FP}}, that is p≥cFP/(cFP+cFN)p\ge c_{\text{FP}}/(c_{\text{FP}}+c_{\text{FN}}), equivalently odds ≥cFP/cFN\ge c_{\text{FP}}/c_{\text{FN}}.

Platt: p^=σ(as+b)\hat p=\sigma(as+b); temperature: p^=softmax(z/T)\hat p=\mathrm{softmax}(\mathbf{z}/T), which for two classes with s=z1−z0s=z_1-z_0 is σ(s/T)\sigma(s/T). For T>0T>0 the order of the logits is kept, so arg⁡max⁡\arg\max is unchanged. The log loss is convex in (a,b)(a,b) and in 1/T1/T, so Newton’s method or any convex solver finds the fit.

Weighted loss: 1N∑iwyiℓi\frac1N\sum_i w_{y_i}\ell_i. If the model family contains the true posterior, then minimizing the weighted loss recovers the posterior for the prior in which class cc has odds multiplied by wcw_c, so with weights w1,w0w_1,w_0 the model’s odds are the true odds times w1/w0w_1/w_0 (for balanced weights, N/(2N1)N/(2N0)=N0N1\frac{N/(2N_1)}{N/(2N_0)}=\frac{N_0}{N_1}, which is (1−π)/π(1-\pi)/\pi when π=N1/N\pi=N_1/N).

Code

The NumPy cells in Try it run in your browser. scikit-learn is not available there, so the block below is shown, not run in the browser. It was run on the machine used for this lesson (scikit-learn 1.8.0) on a made-up 6,000-case data set, and the lines after the # marks show what it printed.

import numpy as np
from sklearn.calibration import CalibratedClassifierCV, CalibrationDisplay, calibration_curve
from sklearn.datasets import make_classification
from sklearn.metrics import brier_score_loss
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn.linear_model import LogisticRegression
from sklearn.utils.class_weight import compute_class_weight

X, y = make_classification(n_samples=6000, n_features=20, n_informative=2,
                           n_redundant=10, random_state=0)
X_fit, X_te, y_fit, y_te = train_test_split(X, y, test_size=0.4,
                                            random_state=0, stratify=y)

raw = GaussianNB().fit(X_fit, y_fit)               # a model known to be over-confident
p = raw.predict_proba(X_te)[:, 1]
frac_pos, mean_pred = calibration_curve(y_te, p, n_bins=5)   # equal-width bins
print("mean predicted:", np.round(mean_pred, 2))   # [0.01 0.29 0.49 0.72 0.99]
print("share positive:", np.round(frac_pos, 2))    # [0.09 0.56 0.52 0.65 0.89]
print("Brier before:", round(brier_score_loss(y_te, p), 3))   # 0.106
CalibrationDisplay.from_predictions(y_te, p, n_bins=10)      # draws the diagram

# Fit the fix on held-out parts of the training data (cv=3), then measure on the test set
for method in ["sigmoid", "isotonic"]:             # "sigmoid" is Platt scaling
    cal = CalibratedClassifierCV(GaussianNB(), method=method, cv=3).fit(X_fit, y_fit)
    q = cal.predict_proba(X_te)[:, 1]
    print(method, "Brier after:", round(brier_score_loss(y_te, q), 3))
    # sigmoid 0.098, isotonic 0.087

# class_weight="balanced" is n_samples / (n_classes * count of the class)
y5 = (np.random.default_rng(0).random(20000) < 0.05).astype(int)
print(compute_class_weight("balanced", classes=np.array([0, 1]), y=y5))   # [ 0.526 10.091]
print(len(y5) / (2 * np.bincount(y5)))                                    # the same
clf = LogisticRegression(class_weight="balanced")

CalibratedClassifierCV with cv=3 fits the base model on two thirds of X_fit and the calibration map on the held-out third, three times, and averages the three calibrated models, so the map is never fitted on the data its model saw. Both fixes lower the Brier score here, and isotonic does a little better on this test set of 2,400 cases (one split, so a small difference should not be over-read). calibration_curve uses the same equal-width bins as this lesson. The balanced weights match the formula.

Try it

Three cells, all NumPy only. The first recomputes the 30-email example, the three-part Brier split and the table of expected scores. The second builds data like the widget’s (its random numbers differ, so its figures differ slightly), compares bin counts, and fits temperature and Platt scaling on a calibration set. The third runs the imbalance experiment and the cost table.

Try it: the 30 emails and the proper scores

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

Try it: bins, then temperature and Platt scaling

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

Try it: a rare class, weights, resampling and the shift

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

Try these changes: in the third cell set the cost of a miss to 20 and see how the best threshold and the costs move; change PREV to 0.01 and see how the recall of the plain model at 0.5 and the gap between the weighted model’s mean probability and the real rate change. In the second cell, set the multiplier 2.5 to 0.5 to build an under-confident model, and check that TT comes out below 1.

Common mistakes

Quiz

Check your understanding

  1. A model said 0.8 for 100 test cases, and 62 of them were positive. What does this bin of the reliability diagram show?

  2. A model has an AUC of 0.9 and is over-confident. You fit temperature scaling on a separate held-out calibration set and apply it to the test set. What happens?

  3. A model was trained on data in which only one in ten of the negative cases was kept, and it says 0.5 for a case. The real data have all the negatives. What is the calibrated probability for the real class ratio?

  4. A missed positive costs 20 and a false alarm costs 1. The model is calibrated. At what probability should you start saying “positive”?

  5. Which of these is NOT a proper scoring rule for probabilities, meaning it can prefer a dishonest report to the true probability?

Exercises

  1. A test set of 200 cases is binned into four bins. The bins hold 100, 50, 30 and 20 cases, with mean predictions 0.1, 0.4, 0.7 and 0.9 and observed shares 0.15, 0.30, 0.50 and 0.85. Compute the ECE.
    Show answerThe gaps are 0.05, 0.10, 0.20 and 0.05, and the weights are 0.5, 0.25, 0.15 and 0.10. So ECE=0.025+0.025+0.030+0.005=0.085\mathrm{ECE}=0.025+0.025+0.030+0.005=0.085. The dots at 0.1 (0.15 observed), 0.7 (0.50) and 0.9 (0.85) are on the over-confident side (above the diagonal on the left, below it on the right). The dot at 0.4 (0.30) goes the other way, so this model is mostly over-confident, not purely.
  2. Six cases have predictions 0.9, 0.8, 0.7, 0.3, 0.2, 0.1 and outcomes 1, 1, 0, 0, 1, 0. Compute the Brier score.
    Show answerThe squared errors are 0.010.01, 0.040.04, 0.490.49, 0.090.09, 0.640.64 and 0.010.01, which sum to 1.281.28. The Brier score is 1.28/6=0.21331.28/6=0.2133.
  3. A data set has 1,000 cases and 50 positives. What are the balanced class weights, and what total weight does each class get?
    Show answerw1=1000/(2⋅50)=10w_1=1000/(2\cdot50)=10 and w0=1000/(2⋅950)=0.526w_0=1000/(2\cdot950)=0.526. Each class has total weight 500: 50⋅10=50050\cdot10=500 and 950⋅0.526=500950\cdot0.526=500.
  4. Why is a plain random split risky for 1,000 cases with 20 positives, and what is the remedy?
    Show answerA random 20% test set has on average 4 positives with a spread of about 1.8, and there is about a 7% chance of at most one, so recall and calibration on the rare class would rest on almost nothing and would change from split to split. A stratified split keeps the share of positives the same in each part (4 in the test set here).
  5. In the widget choose Well calibrated and move the number of bins from 5 to 20. What happens to the ECE and why?
    Show answerIt rises (0.016 with 5 bins, 0.050 with 20 on the starting sample) although the model is honest. With more bins each bin has fewer cases, and the observed share in a bin of few cases is a noisy average, so the gaps become larger by chance.
  6. A model was trained with each positive repeated 4 times and says 0.5 for a case. What probability should you report for the real data?
    Show answerRepeating positives 4 times multiplies the odds the model learns by 4, so the real odds are the model odds divided by 4. The model odds are 1, so the real odds are 0.25 and the probability is 0.25/1.25=0.20.25/1.25=0.2.

Next: P3.A11 covers feature scaling, encoding and data leakage, which includes the leakage traps of resampling before a split. In Part 4, P4.17 returns to why networks become over-confident and what regularization does about it.

Key takeaways

  • A classifier is calibrated if, among the cases where it says pp, about a fraction pp are positive. A reliability diagram checks this on held-out data: bin the predictions, and plot the mean prediction in each bin against the share of positive outcomes. Points below the diagonal on the right mean over-confident, above it mean under-confident. Always show how many cases are in each bin.
  • The expected calibration error (ECE) is the case-weighted average gap between the two in the bins, so it depends on the binning and is not zero even for an honest model (about 0.03 with 1,000 cases and 10 bins). The Brier score (mean squared error of the probabilities) and log loss need no bins and are proper scoring rules: their expected value is lowest when the model reports its true probability. Accuracy is not.
  • Calibration, accuracy and ranking are separate. Multiplying every logit by a positive number changes the calibration and leaves the ranking (AUC) alone; a scorer can rank perfectly and report wrong probabilities; a constant that equals the base rate is calibrated and cannot tell cases apart.
  • Fix calibration on a separate held-out calibration set, not the training set and not the test set: Platt scaling fits σ(as+b)\sigma(as+b) to the scores, temperature scaling fits one number TT and divides the logits by it (it never changes the predicted class), and isotonic regression fits a monotone step function and needs a larger calibration set. These keep the ranking and cannot repair a weak model.
  • With a rare class, accuracy is high for free and a threshold of 0.5 rarely fires. If the probabilities are calibrated, predict positive when p≥cFP/(cFP+cFN)p\ge c_{\text{FP}}/(c_{\text{FP}}+c_{\text{FN}}). Class weights are the same as repeating examples in the loss; resampling and weights make the model's probabilities too high for the real base rate, and multiplying the odds by (true prior odds) divided by (prior odds the model saw) puts them back.
  • Split with stratification so that each part has enough rare cases, resample only the training part after the split, and remember that collecting more minority cases is often the best remedy. SMOTE, which invents synthetic minority cases, is one more option whose benefit varies.
Found a mistake? Tell us