Sub topic 6
Log loss and Brier score
This chapter assumes you know binary classification, train/test splits, and the sigmoid function. It also assumes basic Python with NumPy and scikit-learn. You should have read the chapters on what calibration means and on reading reliability diagrams.
A reliability diagram shows whether probabilities are calibrated, but it does not give a single number. Binning also hides information. Two scoring rules, log loss and the Brier score, give a number per model and reward honest probabilities. This chapter explains how they work, what they capture, and how they fail.
Why a scoring rule must be proper
A scoring rule assigns a penalty to a predicted probability once the true label is known. A rule is proper if the expected penalty is lowest when the model reports its true belief about the label. A model cannot gain by exaggerating or hedging.
Accuracy is not proper in this sense. Predicting 0.51 and predicting 0.99 earn the same credit when both are on the correct side of 0.5. A proper rule separates them.
Both rules in this chapter are strictly proper. If the true probability of a positive is q, the expected loss is minimized only when the model predicts exactly q. That is why they connect to calibration. A model that is off in either direction pays an expected penalty.
Log loss
Log loss, also called cross-entropy or negative log-likelihood, is defined for a binary problem as:
log loss = -(1/N) sum of [ y_i ln(pi) + (1 - yi) * ln(1 - p_i) ]
Here yi is 0 or 1 and pi is the predicted probability of the positive class. For each example, only the probability assigned to the true class matters. If that probability is 0.9, the penalty is -ln(0.9), about 0.105. If it is 0.1, the penalty is -ln(0.1), about 2.30.
The penalty grows without bound as the probability on the true class approaches 0. One confident wrong prediction can dominate the average. For that reason scikit-learn clips probabilities away from exactly 0 and 1 before taking logarithms. Without clipping, a single p = 0 on a positive example gives infinite loss.
Log loss is the quantity that logistic regression minimizes during training. Platt scaling and temperature scaling, covered in later chapters, also minimize it on held-out data.
Brier score
The Brier score is the mean squared error between the predicted probability and the 0/1 outcome:
Brier = (1/N) * sum of (pi - yi)^2
It lies between 0 and 1 for binary problems. Lower is better. The penalty for any single example is at most 1, so one bad prediction cannot dominate. A confident wrong prediction (p = 0.99, y = 0) costs about 0.98, while log loss would charge about 4.6.
A useful baseline is a model that always predicts the base rate. If 30% of examples are positive, that constant model scores 0.3 * 0.7 = 0.21. A model whose Brier score is not clearly below this baseline has learned little.
Comparing the two
| Property | Log loss | Brier score |
|---|---|---|
| Penalty form | -ln of probability on the true class | Squared difference from the outcome |
| Range (binary) | 0 to infinity | 0 to 1 |
| Sensitivity to confident errors | Very high | Bounded |
| Proper | Strictly | Strictly |
| Sensitive to rare, extreme probabilities | Yes | Less so |
| Used as a training or fitting objective | Logistic regression, Platt, temperature scaling | Rarely |
Choose log loss when confident mistakes are costly and you want them punished hard. Choose the Brier score when you want a stable, interpretable number that is not swamped by a few outliers. Reporting both is common.
Calibration and refinement
Both scores mix two effects. For the Brier score, the decomposition is:
Brier = reliability - resolution + uncertainty
- Reliability (also called the calibration term) measures how far predicted probabilities are from the observed frequencies within groups of similar predictions. Lower is better.
- Resolution measures how much the groups' observed frequencies differ from the overall base rate. Higher is better. It rewards a model that separates easy cases from hard ones.
- Uncertainty depends only on the data: baserate * (1 - baserate). No model can change it.
The decomposition is exact only when predictions take a small number of distinct values. With continuous scores, binning makes it approximate.
The consequence is important. A low Brier score or log loss does not prove a model is calibrated. A model with strong resolution can have a small calibration term and still be slightly miscalibrated. A model with poor resolution can be perfectly calibrated and still score poorly. These scores measure overall probability quality. They do not isolate calibration. The expected calibration error, covered in the next chapter, targets the reliability term directly.
Computing both scores
The following script trains a naive Bayes classifier, which is known to produce overconfident probabilities. It prints a binned reliability table and the two scores. It then computes both scores for the constant base-rate baseline.
import numpy as np
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn.calibration import calibration_curve
from sklearn.metrics import brier_score_loss, log_loss
X, y = make_classification(
n_samples=20000, n_features=20, n_informative=5, n_redundant=10, random_state=0
)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.5, random_state=0
)
model = GaussianNB().fit(X_train, y_train)
p = model.predict_proba(X_test)[:, 1]
frac_pos, mean_pred = calibration_curve(y_test, p, 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}")
print("Brier score:", brier_score_loss(y_test, p))
print("Log loss:", log_loss(y_test, p))
base_rate = y_train.mean()
baseline = np.full(len(y_test), base_rate)
print("Baseline Brier:", brier_score_loss(y_test, baseline))
print("Baseline log loss:", log_loss(y_test, baseline))Read the output in three steps.
- Look at the table first. Naive Bayes treats correlated features as independent, so it multiplies evidence that overlaps. The low bins usually sit below the observed rate and the high bins above it, which means the model is overconfident.
- Compare each score with its baseline. The model should beat both. If it does not, the features carry little signal.
- Treat the model's numbers as a starting point. The next chapters repair the overconfidence, and you can then rerun the same scores to check the improvement.
Exact values depend on your library versions, so do not expect to match any quoted figures digit for digit.
Pitfalls
- Evaluating on training data. Both scores look better on data the model has seen. Compute them on held-out data, and for calibrated models on data not used to fit the calibrator either.
- Comparing across datasets. Scores depend on the base rate. A Brier score of 0.10 is good at a 50% base rate and mediocre at a 2% base rate, where the constant baseline is about 0.02 already. Compare against the baseline, not against a fixed threshold.
- Class imbalance. With rare positives, both scores are dominated by the majority class. A model can look good by predicting very low probabilities for everything. Check the reliability diagram and the score on the positive class's region.
- Hard 0 and 1 outputs. Models such as unpruned decision trees return probabilities of exactly 0 or 1. Log loss then punishes every error severely, and clipping hides rather than fixes the problem.
- Small test sets. Log loss has a heavy tail from confident errors, so its estimate is noisy on small samples. Use bootstrap resampling or cross-validation to get an interval.
- Reading a score as calibration. A better score after switching models can come from better resolution rather than better calibration. Look at the reliability diagram too.
Which score to use when
- Use log loss as the primary metric when comparing models that will feed downstream calculations, such as expected cost or a Bayesian update, where tiny probabilities matter.
- Use the Brier score when you want a bounded metric to report to non-specialists, or when rare extreme errors would otherwise swamp the comparison.
- Report both along with a reliability diagram when you evaluate a calibration method. If the two scores rank two models differently, inspect the extreme predictions. The disagreement usually comes from a small number of confident errors.
Exercise
A test set has 1,000 examples and 20% are positive. Model A always predicts 0.2. Model B predicts 0.9 for every positive example and 0.9 for every negative example. What is the Brier score of each model, and what does the comparison tell you?
Show answer
Model A: 0.2 (0.2 - 1)^2 + 0.8 (0.2 - 0)^2 = 0.2 0.64 + 0.8 0.04 = 0.128 + 0.032 = 0.16. Model B: 0.2 (0.9 - 1)^2 + 0.8 (0.9 - 0)^2 = 0.2 0.01 + 0.8 0.81 = 0.002 + 0.648 = 0.65. Model A scores far better. Model B is confident and wrong on most examples, and it has no resolution because it gives the same output for both classes. Model A is calibrated, because 20% of its 0.2 predictions are positive, but it also has no resolution. Its Brier score of 0.16 equals the uncertainty term, so it is the baseline any useful model must beat.
Exercise
A classifier gives p = 0.01 to an example that is actually positive. Compute the log loss and the squared error for that single example, then explain which score is more affected by many such mistakes.
Show answer
Log loss is -ln(0.01), about 4.61. The squared error is (0.01 - 1)^2 = 0.98. Each one is the penalty for one example. Across many such errors, log loss grows much faster because its penalty is unbounded as p approaches 0, while the squared error is capped at 1. Log loss is therefore more sensitive to confident mistakes.
Exercise
Why can a model have a lower Brier score than a competitor yet be less well calibrated?
Show answer
The Brier score equals reliability minus resolution plus uncertainty. The model can have a larger reliability term (worse calibration) but a much larger resolution term (better separation of cases), so its total is lower. A reliability diagram or an expected calibration error estimate would show the calibration gap that the single score hides.