In the KNN lecture, we averaged nearby binary labels to estimate a class probability. We then compared that probability with a cutoff to predict a class. These two steps lead to two different questions: How accurately have we estimated the probability, and how often will the resulting class decision be wrong?
Learning goals
By the end of this lecture, you should be able to:
distinguish a class probability, an estimated probability, and a class decision;
derive the Bayes classifier and explain why it can still make errors;
explain what squared loss and log loss measure for probability predictions;
connect probability bias and variance to classification error; and
explain how unequal error costs change the decision cutoff.
From a probability to a class decision
We start with one predictor and a binary response . Write
Because is either zero or one, its conditional mean is the probability of class 1. A fitted method estimates this probability by . For example, KNN estimates it by the fraction of class-1 observations among the nearest neighbors.
For a cutoff , the fitted class decision is
Here equals one when the condition holds and zero otherwise. We use initially. Whenever we change the cutoff, we will state its value. The same notation works with several predictors by letting represent their observed values.
Two examples show why probability estimation and classification need separate treatment:
Estimates of and give the same class decision, although they express very different probabilities.
Estimates of and are close, but give different class decisions.
Guiding question. How does error in an estimated probability become error in a class decision?
The Bayes classifier
First suppose that we know the true probability . At a fixed predictor value, there are only two possible decisions:
Decision
When is it wrong?
Probability of an error
Predict class 0
Predict class 1
We should predict class 1 when . Thus the Bayes classifier under equal error costs is
At , either decision has the same error probability. Knowing the true probability does not mean knowing the next outcome. If , the Bayes rule predicts class 1 and is still wrong 30 percent of the time at that .
Classification error as expected loss
For a decision rule , the - loss records whether its decision is wrong:
The risk is the expected loss on a new observation. Under - loss, it is the population classification error:
The expectation averages over new predictor values and their outcomes. One test sample estimates this risk; it does not reveal its exact value.
The Bayes rule chooses the smaller conditional error at every , so its risk is
This is the smallest classification error possible with the stated predictors and equal error costs. More training data can help us estimate , but cannot remove the randomness that remains even when is known. Additional informative predictors can reduce this Bayes error.
Later, we will compare fitted KNN decisions with this benchmark. The difference between a fitted rule’s error and the Bayes error will tell us how much additional error comes from using that fitted rule.
Losses for probability predictions
Classification loss only uses the final class label. To assess the numerical probability, we need a loss that uses itself.
Squared loss, or Brier loss
For a probability prediction , the squared loss is . For binary outcomes, this is also called Brier loss. At a fixed ,
The first term does not depend on our prediction. The second is smallest when . Thus reporting the true probability minimizes expected Brier loss.
As we will see in the bias-variance calculation, when is a fitted estimate , averaging the second term over training samples gives squared bias plus variance. This is the same connection between estimation error, bias, and variance that we used for regression.
Log loss
Log loss assigns the loss when and when :
It strongly penalizes a confident prediction of the wrong outcome. If , predicting gives loss about , while predicting gives loss about .
Its conditional expectation is
For , differentiating with respect to gives
The derivative is negative below and positive above it, so expected log loss is also minimized at the true probability. The endpoint cases follow by taking limits.
Log loss will reappear in the next lecture: logistic regression chooses its coefficients by minimizing the average log loss on the training observations.
Loss
Prediction being assessed
What minimizes its conditional expectation?
- loss
A class decision
The more probable class
Brier loss
A probability
The true probability
Log loss
A probability
The true probability
The best class decision can be correct even when the estimated probability is inaccurate. For example, when , any estimate above gives the Bayes decision, but only minimizes the two expected probability losses.
Bias and variance of an estimated probability
Return to the term in the Brier-loss calculation and replace with the fitted estimate . Imagine fitting the same method to many independent training samples. At a fixed , this estimate changes from sample to sample. In the next calculation, expectations and variances of refer to this training-sample variation.
The familiar squared-error identity gives
To see the identity, add and subtract inside the square. The cross term has expectation zero because has mean zero.
For an independent future outcome at this same , the expected Brier loss is therefore
Here the expectation averages over both the training sample and the independent future outcome. The three terms are outcome variation, squared probability bias, and probability variance.
We have now split the second term in the earlier Brier-loss calculation into squared bias and variance. The first term, the variation in a new binary outcome, stays the same.
The irreducible term depends on the loss: belongs to squared loss, while belongs to classification loss. At , these are and , respectively.
A KNN experiment
We use the one-predictor population model
where
Class 1 is unlikely near and increasingly likely in both tails. The probability equals at and . The Bayes rule therefore predicts class 1 outside these boundaries and class 0 between them.
Generate 200 independent training samples, each with observations. Within each sample, use the same observations for every candidate . Evaluate the fitted probabilities on a fixed grid. This grid contains predictor locations, not test outcomes.
The two language versions use the same population model and settings. Their random draws differ. Run the blocks in your chosen language in order.
Repeat the fitting experiment
The array p_hat stores fitted probabilities. Its three axes index training samples, grid locations, and candidate neighbor counts. Each repetition draws new predictors and outcomes. At each grid location, we sort the training observations by distance and average the nearest labels, just as in the KNN lecture.
import numpy as npimport matplotlib.pyplot as pltrng = np.random.default_rng(43206)n =160repetitions =200k_values = np.array([3, 5, 9, 15, 25, 39, 55, 75, 101])x_grid = np.linspace(-2, 2, 241)p_true =1/ (1+ np.exp(-2.5* (x_grid**2-1)))p_hat = np.empty((repetitions, len(x_grid), len(k_values)))for r inrange(repetitions): x = rng.uniform(-2, 2, n) y = rng.binomial(1, 1/ (1+ np.exp(-2.5* (x**2-1))))for i inrange(len(x_grid)): nearest = np.argsort(np.abs(x - x_grid[i]))for j, k inenumerate(k_values): p_hat[r, i, j] = y[nearest[:k]].mean()
Compare the fitted probability curves
Before viewing the figure, compare , , and . Which should vary most across training samples? Which should smooth away the most detail?
The blue curve is the true probability. The orange curve averages the fitted probabilities over training samples. The shaded band contains the middle 80 percent of the fitted probabilities at each location.1
The gap between the orange and blue curves shows bias. The spread of fitted probabilities around their mean shows the training-sample variation measured by the variance term above.
True probabilities and variation in fitted KNN probabilities across 200 training samples.
At , the fitted probabilities vary substantially across training samples. At , the band is narrower and the mean curve still follows the changes near and . At , averaging over broad neighborhoods washes out those changes. The result is lower variance but substantial smoothing bias.
Separate squared bias and variance
At every grid location, estimate squared bias from the mean fitted probability and estimate variance from the spread across repetitions. Then average these quantities over to summarize performance across the population.2
Squared probability bias, variance, and their sum, averaged over the predictor distribution.
The estimated variance generally falls as neighborhoods become larger. Squared bias rises sharply for large neighborhoods. Their sum is smallest at a moderate . The irreducible Brier component, averaged over , is about for every . Adding it shifts the entire MSE curve upward without changing which is best in this comparison.
How probability error becomes classification error
Recall the opening examples: estimates of and give different decisions, while and give the same decision. This is why the squared-loss decomposition does not carry over directly to - loss. A probability error changes a decision only if it moves the estimate across the cutoff.
Fix a decision rule . At a particular , agreeing with the Bayes decision adds no error. If but , the extra conditional error is
If but , it is . Combining these cases and averaging gives
This is the excess classification error: the error above the Bayes benchmark. It depends on where the classifier disagrees with the Bayes rule and how costly each disagreement is.
Near , a small probability change can reverse the decision, but the extra error from that reversal is small.
Far from , reversing the decision requires a larger probability error, and the extra error is larger.
For example, predicting class 0 when adds to the conditional error. Making the same decision when adds .
Return to the KNN experiment
Because we know in the simulation, we can calculate each fitted rule’s conditional error directly: use where it predicts 0 and where it predicts 1. Averaging over the grid approximates population classification error. This isolates variation caused by the training sample without adding random test outcomes.
plt.figure(figsize=(8, 5))plt.boxplot([error[:, np.flatnonzero(k_values == k)[0]] for k in [5, 25, 75]], tick_labels=[5, 25, 75], patch_artist=True, boxprops={"facecolor": "lightblue"}, medianprops={"color": "black"})plt.axhline(bayes_error, color="black", linestyle="--", linewidth=2, label="Bayes error")plt.xlabel("Number of neighbors k")plt.ylabel("Population classification error")plt.legend(loc="upper left", frameon=False)plt.tight_layout()plt.show()
Approximate population classification errors across 200 fitted KNN models. The dashed line is the Bayes error.
The Bayes error is about . At , fitted probabilities fluctuate because each estimate uses few observations. At , the fitted curves follow the population pattern more closely. At , strong smoothing puts a broad part of the mean fitted curve near , so changes in the training sample can move many decisions across the cutoff.
Lower probability variance therefore does not guarantee more stable class decisions. Its effect depends on where the fitted probabilities lie relative to the cutoff.
Unequal error costs
So far, false positives and false negatives have equal cost. Suppose instead that a false positive costs , a false negative costs , and correct decisions have zero cost.
We repeat the Bayes comparison of the two possible decisions, now using these costs in place of - loss.
At a fixed , predicting 1 has expected cost , while predicting 0 has expected cost . Choose class 1 when
or equivalently when
If a false negative costs four times as much as a false positive, the cutoff is . We accept more positive decisions because missing a positive case is more costly. In practice, we substitute an estimated probability and examine the consequences of the chosen cutoff. That is the subject of the next lecture.
A note on imbalanced classes
Class imbalance alone does not change the Bayes cutoff under equal error costs when is the conditional probability in the population of interest. Those probabilities already reflect the class prevalence. A different cutoff follows from different costs or a different decision objective. If training observations were deliberately sampled to change the class proportions, the fitted probabilities may need adjustment before applying a probability-based decision rule.
Check your understanding
If , what is the Bayes decision and its conditional error? What changes if we estimate this probability by ?
Why are the irreducible Brier loss and Bayes classification error different?
How do the KNN probability bands and bias-variance curves explain the effect of increasing ?
Why can a low-variance probability estimate still produce unstable class decisions?
What happens to the optimal cutoff when false negatives become more costly?
Key ideas
A probability estimate and a class decision are different predictions.
The Bayes classifier minimizes expected - loss, but overlapping classes still create errors.
Brier loss and log loss reward accurate probabilities. Squared probability error has the familiar bias-variance decomposition.
Classification error depends on whether probability errors change the decision and how far the true probability lies from the cutoff.
The costs of the two kinds of error determine the appropriate decision rule.
This is a pointwise description of variation across fitted models, not a confidence band for the true probability curve.↩︎
The equally spaced grid and half weights at its endpoints implement the trapezoidal rule for the uniform predictor distribution. For the finite simulation, variance uses the number of repetitions as its divisor, so the calculated MSE equals squared bias plus variance exactly. These remain Monte Carlo estimates of the corresponding population quantities.↩︎