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 that the case is positive (), calibrated means
Read it as: among the cases where the model says , the share that are positive is . 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 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 , and . 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:
- Collect the predictions and outcomes on data the model was not trained on (P3.A4). On its own training data an overfit model looks better than it is.
- Cut into bins of equal width. Bin (counting from 0) holds the cases with , and the last bin also holds .
- For each bin that has cases, compute the count , the mean prediction and the share of positives .
- Plot together with the diagonal, and show (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 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 : makes every prediction more extreme, 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.
Things to try, in order:
- 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).
- 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.
- 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.
- 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.
- 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.
- 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, cases in all and in bin :
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 . 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):
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 , the ten at 0.5 give , and the ten at 0.2 give . The total is 8.00, so the Brier score is . 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:
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 nats of log loss, which has no upper limit as the prediction approaches 1, but only 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 , and you report . 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 | log loss | Brier | abs. error |
|---|---|---|---|
| 0.5 | 0.693 | 0.250 | 0.500 |
| 0.7 | 0.526 | 0.170 | 0.380 |
| 0.8 | 0.500 | 0.160 | 0.320 |
| 0.9 | 0.545 | 0.170 | 0.260 |
| 0.99 | 0.929 | 0.196 | 0.206 |
Each column is the expected score of one rule (abs. error is ).
Log loss and Brier are lowest at . The absolute error is not proper: it is lowest at and would reward a model that exaggerates (the expected value is , which keeps falling until ). Accuracy is also not proper: any 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 cases having prediction , share positive, and base rate overall, the Brier score splits exactly into three terms:
Reliability is the squared version of the calibration gap (smaller is better). Resolution 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 is the Brier score of always saying the base rate, and nothing about the model changes it. For the 30 emails, with base rate : . 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 , 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 (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:
Two numbers: stretches or squeezes the score, 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 and : it squeezes the logits by a factor of about (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 with , so there is one number, the temperature :
For several classes the same idea is .
pulls probabilities toward the middle (it fixes over-confidence), pushes them outward. For the logits of a three-class model, softmax (P3.A8) gives at , at and at . 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 , 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
balancedclass 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:
| model | mean | recall | ECE |
|---|---|---|---|
| plain | 0.049 | 0.092 | 0.003 |
| weights | 0.335 | 0.780 | 0.285 |
| under | 0.331 | 0.775 | 0.281 |
| over | 0.337 | 0.782 | 0.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 and a false alarm costs , the best rule says “positive” when
This holds when 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 . 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:
where is the loss on one case and 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
with cases, classes and cases in class . In the example , , and the positives get and the negatives . 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
where is the share of positives. Weights and resampling change the prior the model learns from, to a new value (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:
In the example and , so the odds are multiplied by . 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 (these are odds), a probability of 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 the model’s odds. A model value of 0.5 (odds 1) means odds 0.1, a probability of .
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: . ECE with equal-width bins: .
Proper scores for a case with true and reported . Write for the expected squared error:
For the log loss of one case, , the expected value is
Both are minimized at : the first because of the square, the second by Gibbs’ inequality (P1.E4). The absolute error has , which is linear in , so for it is smallest at , not at .
Cost threshold: say positive iff , that is , equivalently odds .
Platt: ; temperature: , which for two classes with is . For the order of the logits is kept, so is unchanged. The log loss is convex in and in , so Newton’s method or any convex solver finds the fit.
Weighted loss: . If the model family contains the true posterior, then minimizing the weighted loss recovers the posterior for the prior in which class has odds multiplied by , so with weights the model’s odds are the true odds times (for balanced weights, , which is when ).
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.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
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 comes out below 1.
Common mistakes
Quiz
Check your understanding
A model said 0.8 for 100 test cases, and 62 of them were positive. What does this bin of the reliability diagram show?
The mean prediction is 0.8 and the observed share is 0.62, so the dot is below the diagonal on the right, which is the over-confident side (predictions farther from 0.5 than the outcomes). Under-confident would put the dot above the diagonal at this end. A gap of 0.18 is large for 100 cases (the noise for one bin of that size is about 0.04), so it should not be waved away as calibration. A single bin says nothing about the AUC, which needs the whole ranking.
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?
Dividing the logits by a positive keeps the order of the scores, so the AUC is unchanged, and when is above 1 it pulls the probabilities toward the middle, which is what an over-confident model needs, so the ECE falls. Honest numbers do not improve the ranking. The model is the same, but its reported probabilities are not, and the ECE measures those.
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?
Keeping one negative in ten makes the positives look ten times as common, so the model odds are ten times too high. The model value 0.5 has odds 1, the true odds are 0.1, and the probability is 0.1/1.1, which is 0.091. A probability does depend on the class ratio, through the prior odds in Bayes' theorem, which is exactly what resampling disturbed. Multiplying the odds by ten would repeat the mistake in the wrong direction.
A missed positive costs 20 and a false alarm costs 1. The model is calibrated. At what probability should you start saying “positive”?
Saying positive costs (1 - p) times 1, and saying negative costs p times 20, so the break-even is p = 1/(1 + 20) = 1/21. The threshold 0.5 is right only when the two mistakes cost the same. Using 20/21 turns the costs around, which would suppress almost every alarm. The calibrated probability already contains the class balance, so the threshold depends on the costs and not on whether the data are balanced.
Which of these is NOT a proper scoring rule for probabilities, meaning it can prefer a dishonest report to the true probability?
Accuracy gives the same value for any report above 0.5, so it cannot tell an honest 0.8 from an inflated 0.99. The Brier score and log loss are both proper: for a true probability of 0.8 their expected values are lowest at a report of 0.8.
Exercises
- 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 answer
The 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 . 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. - 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 answer
The squared errors are , , , , and , which sum to . The Brier score is . - A data set has 1,000 cases and 50 positives. What are the
balancedclass weights, and what total weight does each class get?Show answer
and . Each class has total weight 500: and . - Why is a plain random split risky for 1,000 cases with 20 positives, and what is the remedy?
Show answer
A 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). - In the widget choose Well calibrated and move the number of bins from 5 to 20. What happens to the ECE and why?
Show answer
It 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. - 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 answer
Repeating 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 .
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.