3 Supervised Learning, Prediction, and Evaluation

On this page

Supervised learning uses examples \((x_i,y_i)\), where both the features \(x_i\) and the outcome \(y_i\) are observed, to learn a prediction rule. Given the features of a new case, this rule predicts its unknown outcome. The observed outcomes provide the supervision: they let us measure prediction errors and use these errors to fit the rule.

This chapter studies prediction rules, their losses, and the classes from which we choose them. We consider regression, nominal classification, and ordinal prediction using constant rules and rules based on affine functions. After these three prediction problems, we return to regression to study how nearest neighbors and polynomial degree control flexibility. Regularization provides another way to control it. Finally, validation and test data help us choose and assess a fitted rule, including when classes are imbalanced.

3.1 Prediction, loss and risk

We formulate supervised prediction as a statistical decision problem with four components: a random feature vector \(X \in \Xset\), an outcome \(Y\in \Yset\), a prediction function \(f:\Xset\to\Aset\), and a loss function \(\lscr\). The set \(\Aset\) is the prediction set: it contains the objects our rule is allowed to output. In regression this is usually \(\R\); in classification it can be a set of labels, a vector of class scores, or a vector of class probabilities.

Sometimes the object returned by \(f\) is not itself the final label or value we report to the user. We then use a decision map

\begin{align*} d:\Aset\to\Yset, \qquad \hat y = d(f(x)). \tag{3.1.1} \end{align*}

For example, in classification \(f(x)\) may be a vector of class probabilities, while \(d(f(x))\) is the class with largest probability. To compare a prediction with an observed outcome, we use a label-lifting map

\begin{align*} r:\Yset\to\Aset \tag{3.1.2} \end{align*}

that embeds \(y\) into the prediction set. We choose \(r\) so that \(d(r(y))=y\).1In general \(r(d(a))\neq a\): a hard label does not contain enough information to reconstruct a probability vector or score vector. In regression, usually \(\Aset=\Yset=\R\), and both \(d\) and \(r\) are the identity.

The loss function

\begin{align*} \lscr:\Aset\times\Aset\to\R_+ \end{align*}

assigns a cost \(\lscr(r(y), f(x))\) to predicting \(f(x)\) when the observed outcome is represented by \(r(y)\). The order matters: losses need not be symmetric. The loss specifies the costs of different errors in the application. We will always take it to be nonnegative, and usually zero for a perfect prediction. In regression, where differences such as \(y-\hat y\) are meaningful, common losses increase as the prediction moves farther away from the observed value. In classification, the prediction may be a label or a probability vector, so the loss need not be based on numerical distance.

Let \(F_{X,Y}\) be the joint distribution of \(X\) and \(Y\). This distribution is typically unknown, but it is useful as the population from which the samples in the training set

\begin{align*} \Tset = [(x_1, y_1), \ldots, (x_n, y_n)] \end{align*}

are assumed to be drawn independently. Here \(x_i\) is a feature vector2Also called a vector of predictors, covariates, regressors, explanatory variables, or inputs. The precise name depends on the field and on whether the task is predictive or causal. and \(y_i\) is the observed outcome3Also called the target, response, label, dependent variable, or supervisory signal.. The \(j\)th feature coordinate of \(x\) is written as \(x(j)\). The pair \((x_i, y_i)\) is called a sample. We write \(\Tset\) as a list rather than a set because the same sample may occur more than once.4We will later see that bootstrap samples can contain the same sample multiple times. The order in \(\Tset\) itself has no meaning; it only lets us refer to sample \(i\).

The assumption that the training samples and future samples come from the same distribution matters. If the population changes after fitting, then a predictor can perform poorly on new5By new we mean an observation that does not occur in the training set \(\Tset\). observations even when it did not overfit the training set. This problem is called distribution shift. Here we assume that the distributiion function \(F_{X,Y}\) remains the same.

For a fixed prediction function \(f\), the population risk under the loss \(\lscr\) is

\begin{align*} R(f) = \E{\lscr(r(Y), f(X))} = \int \lscr(r(y), f(x)) \,\mathrm d F_{X,Y}(x,y). \tag{3.1.3} \end{align*}

This is the expected loss on a new sample from the population. The Bayes optimal predictor for the chosen loss is

\begin{align*} f^{*} \in \argmin_f R(f) = \argmin_f \E{\lscr(r(Y), f(X))} \tag{3.1.4} \end{align*}

The value \(R(f^*)\) is called the Bayes risk. It is the smallest risk attainable for the prediction problem under the chosen loss, hence it is the irreducible risk that remains even for an optimal predictor.

If \(F_{X,Y}\) were known and the optimization over all prediction functions were feasible, the Bayes predictor would be the natural target. In practice we only have the training set \(\Tset\), so we replace the population risk by the training risk

\begin{align*} \hat R_{\Tset}(f) = \frac{1}{n}\sum_{i=1}^{n} \lscr(r(y_i), f(x_i)). \end{align*}

This leads to the optimization problem

\begin{align*} \argmin_f \hat R_{\Tset}(f). \end{align*}

If we minimize training risk over all possible functions, the result can fit the training samples perfectly while performing arbitrarily poorly on new samples. We want the predictor to generalize: it should also have low risk on new samples drawn from \(F_{X,Y}\).

We therefore restrict the search to a model class \(\Fset\), a specified set of prediction functions.6A model is just a function, but in machine learning the word model is often used for the fitted prediction rule together with its parametrization or construction method. The model class determines which rules can be fitted. A restrictive class allows only crude, but robust, fits; a large class may also contain functions that fit random variation in the training sample. Finding a good model space is an important part of the fitting process.

We begin with constant rules and rules based on affine functions. The constant model class is

\begin{align*} \Fset_{\mathrm{const}}=\{f_c:c\in\Aset\},\qquad f_c(x)=c, \end{align*}

that is, each rule returns the same prediction for every feature vector. The prediction \(c\) can be a numerical value or a probability vector, depending on the prediction set.

For numerical features \(x\in\Xset\subseteq\R^p\), the class of real-valued affine rules is7\(\ip{\beta, x} = \sum_i \beta_i x_i\), i.e., the inner product.

\begin{align*} \Fset_{\mathrm{aff}} =\{f_{\beta_0,\beta}:\beta_0\in\R,\beta\in\R^p\}, \qquad f_{\beta_0,\beta}(x)=\beta_0+\ip{\beta,x}. \end{align*}

In regression, this value is the prediction itself. In classification, we use affine functions as scores and transform them into probabilities, as described below. The resulting probability predictions are generally not affine functions of \(x\).

Later chapters consider more flexible model classes, such as trees and neural networks.

The restriction of the optimization to \(\Fset\) gives two more prediction rules besides the Bayes predictor:

\begin{align*} f_{\Fset}^{*} &\in \argmin_{f\in \Fset} R(f), & f_{\Tset}^{*} &\in \argmin_{f\in \Fset} \hat R_{\Tset}(f). \tag{3.1.5} \end{align*}

The function \(f_{\Fset}^{*}\) is the best-in-class predictor: it is the best rule in \(\Fset\) for the true population risk. The function \(f_{\Tset}^{*}\) is the empirical risk minimizer: it is the rule in \(\Fset\) with the smallest training risk. Since the Bayes predictor optimizes over all prediction functions, while \(f_{\Fset}^{*}\) optimizes only over \(\Fset\), we have

\begin{align*} R(f_{\Fset}^{*}) \ge R(f^*). \end{align*}

These definitions give the standard decomposition of the excess risk:

\begin{align*} R(f_{\Tset}^{*}) - R(f^{*}) &= \underbrace{R(f_{\Tset}^{*}) - R(f_{\Fset}^{*})}_{\text{estimation error}} + \underbrace{R(f_{\Fset}^{*}) - R(f^{*})}_{\text{approximation error}}. \tag{3.1.6} \end{align*}

The estimation error results from choosing a rule that optimizes \(\hat R_{\Tset}\) rather than \(R\).8Mind the difference: \(f^*_\Fset \neq f^*_\Tset\); one uses \(\Fset\), the other \(\Tset\). The approximation error is the increase in risk caused by restricting the optimization to the model class \(\Fset\). If \(\Fset\) is too small, even the best rule in the class cannot achieve a risk close to the Bayes risk.

This decomposition explains a tradeoff in model choice. Enlarging \(\Fset\) can reduce the approximation error, because we minimize risk over more functions. But a larger class can also increase the estimation error, because the empirical risk minimizer can adapt more strongly to random noise in \(\Tset\). The training risk \(\hat R_{\Tset}(f_{\Tset}^{*})\) cannot increase when \(\Fset\) is enlarged, but the population risk \(R(f_{\Tset}^{*})\) can.9To be explicit, note how \(\hat R_{\Tset}\) and \(R\) are used here. This is the overfitting problem.

Many texts discuss this tradeoff in terms of bias and variance. The usual bias-variance decomposition is a squared-loss identity that averages over possible training samples. It separates risk in a different way from the approximation/estimation decomposition above. We derive it when we specialize to squared loss below.

The next three sections apply the above definitions to

regression andnominal classification.

3.2 Regression

Regression problems aim to predict numerical values such as a price, a travel time, or a demand level.10Wikipedia: Regression analysis. Therefore, in a regression problem, \(\Yset=\Aset=\R\), and the decision map \(d\) and label-lifting map \(r\) are identity maps.11In classification problems, this is no longer the case. For a prediction function \(f:\Xset\to\R\), the prediction error on a case is \(Y-f(X)\); the squared

loss below is a function of this error.

We now consider the squared loss. We first derive the Bayes predictor, then find the best predictors within the constant and affine model classes. Replacing population risk by training risk gives practical fitting procedures: squared loss leads to the sample mean and ordinary least squares.

3.2.1 Squared loss

The most common loss for regression is squared loss,

\begin{align*} \lscr(y, \hat y) &= \frac{1}{2}(y-\hat y)^2, & \hat y &= f(x). \end{align*}

The empirical average squared error is reported as the mean squared error (MSE):

\begin{align*} \mathrm{MSE}_{\Sset}(f) = \frac{1}{|\Sset|}\sum_{(x,y)\in \Sset}(y-f(x))^2, \end{align*}

Thus, the empirical risk is half the MSE. In practice one often reports the root mean squared error (RMSE), the square root of the MSE, which has the same units as \(y\); see Wikipedia: Mean squared error.

To find the optimal rule for this loss, suppose we know \(F_{X,Y}\) and may choose any prediction function. As a first step, we decompose the squared risk in a way that will be useful throughout this section. It separates the part of the error that can be reduced by choosing a better prediction rule from the variation in \(Y\) that remains once \(X\) is known.

Theorem 3.2.1.

Let \(m(x) = \E{Y \mid X=x}\) be the conditional expectation of \(Y\) given \(X=x\), and suppose \(\E{Y^{2}}<\infty\). Then, for every \(f:\Xset\to\R\) with \(\E{f(X)^{2}}<\infty\),

\begin{align*} R(f)=\frac{1}{2}\E{(Y-f(X))^{2}} &= \underbrace{\frac{1}{2}\E{\rb{m(X)-f(X)}^{2}}}_{\text{excess risk of \(f\)}} + \underbrace{\frac{1}{2}\E{\V{Y|X}}}_{\text{irreducible risk}}. \tag{3.2.1} \end{align*}
Proof

Write the prediction error \(Y-f(X)\) as \((Y-m(X))+(m(X)-f(X))\):

\begin{align*} \frac{1}{2}\E{(Y-f(X))^{2}} &= \frac{1}{2}\E{\rb{\rb{Y-m(X)} + \rb{m(X)-f(X)}}^{2}} \\ &= \frac{1}{2}\E{\rb{m(X)-f(X)}^{2}} + \E{\rb{m(X)-f(X)}\rb{Y-m(X)}}\\ &\quad + \frac{1}{2}\E{\rb{Y-m(X)}^{2}}. \end{align*}

By conditioning on \(X\) in the middle term,

\begin{align*} \E{\rb{m(X)-f(X)}\rb{Y-m(X)} \given X} = \rb{m(X)-f(X)} \E{Y-m(X) \given X}= 0, \end{align*}

because \(m(X) = \E{Y \given X}\).

With respect to the third term, conditioning on \(X\) yields

\begin{align*} \E{\rb{Y-m(X)}^{2}\given X} &= \E{Y^{2}\given X} - 2m(X)\E{Y\given X} + m(X)^{2}\\ &= \E{Y^{2}\given X} - m(X)^{2}. \end{align*}

From the definition of conditional variance

\begin{align*} \V{Y\mid X} &= \E{(Y-\E{Y\mid X})^{2}\mid X} = \E{Y^{2}\mid X} - m(X)^{2}. \end{align*}

Taking expectations completes the proof.

The Bayes regressor12That is, the Bayes optimal predictor (3.1.4) for a regression problem. under squared loss now follows easily.

Corollary 3.2.2.

Under the same conditions on a function \(f\) as Th. 3.2.1, \(R(f) \geq R(m)\). Consequently, the conditional expectation \(f^{*}(x) = m(x) = \E{Y \mid X=x}\) attains the Bayes risk \(R(f^{*}) = R(m) = \frac{1}{2}\E{\V{Y\mid X}}\).

From Eve’s law13Eve’s law, also known as the law of total variance, states that \(\V Y = \E{\V{Y\mid X}} + \V{\E{Y\mid X}}\). I prefer the name Eve’s law because it is a law. it is immediate that \(R(f^{*}) \leq \frac{1}{2}\V Y\).

Fitting the best constant function requires minimizing \(\frac{1}{2}\E{(m(X) -c)^2}\) in (3.2.1). Expanding the square and using that \(\E{m(X)} = \E Y\), gives

\begin{align*} \frac{1}{2}\E{m(X)^{2}} +\frac{1}{2}c (c-2 \E Y). \end{align*}

This is minimal at \(c^* = \E Y\), and then the risk \(R(c^*)\) becomes

\begin{align*} c^{*} &= \E Y, & R(c^*) &= \frac{1}{2}\E{\V{Y\mid X}} + \frac{1}{2}\E{m(X)^{2}} - \frac{1}{2}(\E Y)^{2} = \frac{1}{2}\V Y, \tag{3.2.2} \end{align*}

where the last step follows from Eve’s law.

To obtain the empirical risk minimizer and minimal empirical risk, we replace \(F_{X,Y}\) by the measure induced by \(\Tset\) to get

\begin{align*} \hat c &= \hat y = \frac{1}{|\Tset|}\sum_{(x,y)\in\Tset}y, & \hat R_{\Tset}(\hat c) &= \frac{1}{2|\Tset|}\sum_{(x,y)\in\Tset}(y-\hat c)^2. \tag{3.2.3} \end{align*}

Fitting an affine prediction rule minimizes the excess-risk term in (3.2.1):

\begin{align*} \frac{1}{2}\E{\rb{m(X)-f_{\beta_0,\beta}(X)}^2}, \quad f_{\beta_{0}, \beta}(x) = \beta_0-\ip{\beta,x}. \end{align*}

Setting the partial derivatives wrt \(\beta\) and \(\beta_0\) to zero gives the population normal equations:

\begin{align*} \beta_0 + \ip{\beta, \E{X}} &= \E Y,\\ \E{\rb{m(X)-\beta_0-\ip{\beta,X}}X(j)} &= 0, \qquad j=1,\ldots,p. \end{align*}

Replacing \(F_{X,Y}\) by the measure induced by \(\Tset\) gives

\begin{align*} \hat\beta_0 + \ip{\hat\beta,\hat x} &= \hat y,\\ \sum_{(x,y)\in\Tset}\rb{y-\hat\beta_0-\ip{\hat\beta,x}}x(j) &= 0, \qquad j=1,\ldots,p. \end{align*}

These solve the ordinary least squares (OLS) problem:

\begin{align*} (\hat\beta_0,\hat\beta) &\in\argmin_{\beta_0,\beta}\hat R_{\Tset}(f_{\beta_0,\beta}), \tag{3.2.4} \\ \hat R_{\Tset}(f_{\beta_0,\beta}) &=\frac{1}{2|\Tset|}\sum_{(x,y)\in\Tset} \rb{y-\beta_0-\ip{\beta,x}}^2. \tag{3.2.5} \end{align*}

Restricting the affine class to \(\beta=0\) recovers the constant class: the population equation gives \(\beta_0^*=\E{Y}\) and the sample equation gives \(\hat\beta_0=\hat c\) of (3.2.3).

Bias and variance are two forms of error that appear through the approximation of \(m(x)\) by the empirical risk minimizer \(\hat f_\Tset\), (3.1.5). Write14An expectation with subscript \(\Tset\) averages over training samples.

\begin{equation*} \bar f(x)=\EE{\Tset}{\hat f_{\Tset}(x)} \tag{3.2.6} \end{equation*}

for the average prediction at \(x\) over the iid training samples that can obtained from \(F_{XY}\). The bias is \(\bar f(x)-m(x)\): the systematic discrepancy between the average fitted prediction and the conditional mean.15Recall from Cor. 3.2.2 that \(m(x)\) is precisely the Bayes regressor. The variance measures how much the fitted prediction16Note, the observation \(x\) is fixed here; the randomness comes from \(\Tset\). \(\hat f_{\Tset}(x)\) changes when we draw a new training sample.

There are two sources of randomness to distinguish. The training samples determine the fitted rule; a new observation \((X^0,Y^0)\), independent of \(\Tset\) and with distribution \(F_{X,Y}\), determines where and against which outcome we evaluate that rule.

Theorem 3.2.3.

The risk of the empirical risk minimizer can be decomposed as:17Note, all outer expectation are taken with respect to \(X\).

\begin{align*} \EE{\Tset}{R(\hat f_{\Tset})} &=\underbrace{\frac{1}{2}\E{\V{Y\mid X}}}_{\text{irreducible risk}} +\underbrace{\frac{1}{2}\E{\rb{\bar f(X)-m(X)}^{2}}}_{\text{squared bias}} +\underbrace{\frac{1}{2}\E{\VV{\Tset}{\hat f_{\Tset}(X)}}}_{\text{variance}}. \tag{3.2.7} \end{align*}
Proof

Fix \(x\). In the first term in (3.2.1) add and subtract the average fitted prediction to get

\begin{align*} m(x)-\hat f_{\Tset}(x) =\bigl(m(x)-\bar f(x)\bigr) +\bigl(\bar f(x)-\hat f_{\Tset}(x)\bigr). \end{align*}

Squaring, expanding and taking the expectation over \(\Tset\) gives

\begin{align*} (m(x)-\bar f(x))^2 +2(m(x)-\bar f(x)) \EE{\Tset}{\bar f(x)-\hat f_{\Tset}(x)} +\EE{\Tset}{(\bar f(x)-\hat f_{\Tset}(x))^2}. \end{align*}

The cross term vanishes: by the definition of \(\bar f\) in (3.2.6),

\begin{align*} \EE{\Tset}{\bar f(x)-\hat f_{\Tset}(x)} =\bar f(x)-\EE{\Tset}{\hat f_{\Tset}(x)}=0. \end{align*}

The third term is the variance of the fitted prediction across training samples.

Taking the expectation over a new observation \(X\), combining this with (3.2.1), and using the independence of \(X\) and \(\Tset\) proves the result.

Feature selection affects both bias and variance. Suppose for this paragraph that the feature coordinates are uncorrelated, so that leaving one out does not disturb the estimates of the others. A feature with \(\beta_{j}=0\) has no contribution to the conditional mean, so estimating its coefficient adds variance without reducing bias. Omitting it therefore lowers the variance of the fitted rule without increasing bias. Omitting a feature with \(\beta_{j}\neq0\) leaves its contribution \(\beta_{j}x(j)\) inside the residual

\begin{align*} y-\hat\beta_0-\sum_{k\neq j}\hat\beta_k x(k) \end{align*}

of the reduced fit. This raises the residual variance, and every remaining coefficient is estimated against that larger noise; omitting it therefore raises the variance of the remaining estimates and introduces bias. Feature selection aims to retain useful features and omit those that add only estimation noise. The lasso in Section 3.5 is one method for selecting relevant features.

3.3 Nominal classification

Nominal classification problems have categorical labels without a natural order. This means that for \(K\)-class nominal classification, the label lies in the set18It is common to assume that labels like ’red’ and ’green’ are already converted to numbers.

\begin{align*} \Yset = \Kset=\set{1,\ldots,K}. \end{align*}

Besides the prediction \(\hat y\) for the label \(y\), we will be concerned with /probability prediction

\begin{align*} \hat p = (\hat p_1,\ldots,\hat p_K) \in \Delta_K, \end{align*}

where \(\Delta_{K}\) is the probability simplex

\begin{align*} \Delta_K = \set{p\in\R^K : p_k\geq 0,\ \sum_{k=1}^{K} p_k = 1}. \end{align*}

Here \(\hat p_k\) is interpreted as the predicted probability of class \(k\).

Throughout this section the prediction set \(\Aset=\Delta_K\), and the fitted rule returns \(\hat a = \hat p\). When a single class has to be returned based on \(\hat p\), the decision map is the argmax rule19This rule is the same as majority vote when \(\hat p\) is the vector of class frequencies of a sample list \(\Sset\): the label with the highest probability is then the most frequent one.

\begin{align*} \hat y = d(\hat p) \in \argmax_{k} \hat p_k. \tag{3.3.1} \end{align*}

In the other direction, the observed class \(y\) is lifted into the simplex by the one-hot encoding of \(y\),

\begin{align*} a = q = r(y), \qquad q_k=\1{y=k}, \end{align*}

which puts probability one on the observed class and zero on all others.20Observe that, as required, \(d(r(y))=y\).

For any list \(\Sset\) whose labels lie in \(\Kset\), \(\Sset_{k} = \qb{(x,y)\in\Sset : y=k}\) is the sublist of samples of class \(k\). Write \(p\) for the vector with components21That is, the marginal probabilities. \(p_{k} = \P{Y=k}\), and \(p(x)\) be the vector of conditional class probabilities with components \(p_{k}(x) = \P{Y=k \mid X=x}\). For the non-empty training list \(\Tset\), write \(\Tset_k=\qb{(x,y)\in\Tset:y=k}\) and \(\hat p_k=|\Tset_k|/|\Tset|\).

3.3.1 Zero-one loss

Zero-one loss compares samples based on class:

\begin{align*} \lscr(a, \hat a) = \lscr(q, \hat p) = \1{d(q) \neq d(\hat p)} = \1{y \neq d(\hat p)}. \tag{3.3.2} \end{align*}

The next numerical example shows an important problem with zero-one loss. Take two classes, \(K=2\), and suppose the observed class is \(y=1\), which converts into the one-hot vector \(q=(1,0)\). Compare the two probability predictions

\begin{align*} \hat p^{A} &= (0.51,0.49), & \hat p^{B} &= (0.99,0.01). \end{align*}

The two predictions receive the same zero-one loss, but this loss does not show confident the probability vector is. As a consequence, optimizing under zero-one loss is difficult because small changes in the probabilities often leave the predicted label unchanged.

For any rule \(f:\Xset\to\Delta_K\) write \(g=d\circ f : \Xset \to \Kset\). Then for the conditional risk

\begin{align*} \E{\lscr(r(Y),f(X))\mid X=x} &= \E{Y \neq g(X) \mid X=x} \\ &= \P{Y \neq g(X) \mid X=x} \\ &= 1 - \P{Y = g(X) \mid X=x}. \end{align*}

Therefore,

\begin{align*} \argmin_{g} \E{\1{ Y \neq g(X)|X=x}} = \argmax_{k\in K} \P{Y=k |X=x}. \end{align*}

Using (3.3.1), we see that the Bayes classifier \(f^*\) has components

\begin{align*} f^{*}_{k}(x) = \P{Y=k \mid X=x} = p_{k}(x). \tag{3.3.3} \end{align*}

For a constant predictor \(d(f(x)) =k\), the loss becomes

\begin{align*} R(f) = \E{Y\neq k} = 1-\P{Y=k}. \end{align*}

Thus the best constant predictor is the majority class and the risk is the misclassification rate,

\begin{align*} \hat y &\in \argmax_{k} |\Tset_{k}|, & \hat R_{\Tset}(r(\hat y)) &= 1 - \max_{k} \hat p_{k}. \tag{3.3.4} \end{align*}

3.3.2 Brier loss

The Brier loss22Wikipedia: Brier score.

\begin{align*} \lscr(q,\hat p) = \sum_{k=1}^{K}(q_k-\hat p_k)^2 \tag{3.3.5} \end{align*}

compares the one-hot representation \(q=r(y)\) to the prediction \(\hat p\).

A numerical example shows the advantage of Brier loss over zero-one loss. Take two classes, \(K=2\), and suppose the observed class is \(y=1\), which converts into the one-hot vector \(q=(1,0)\). Compare the two probability predictions

\begin{align*} \hat p^{A} &= (0.51,0.49), & \hat p^{B} &= (0.99,0.01). \end{align*}

For the Brier loss, both probability components enter the loss. For \(\hat p^{A}\),

\begin{align*} \lscr(q,\hat p^{A}) &= (q_1-\hat p^{A}_{1})^{2} + (q_2-\hat p^{A}_{2})^{2} \\ &= (1-\hat p^{A}_{1})^{2} + (0-\hat p^{A}_{2})^{2} \\ &= (1-0.51)^2 + (0-0.49)^2 \\ &= 0.49^2 + 0.49^2 \\ &\approx 0.48. \end{align*}

For \(\hat p^{B}\),

\begin{align*} \lscr(q,\hat p^{B}) &= (q_1-\hat p^{B}_{1})^{2} + (q_2-\hat p^{B}_{2})^{2} \\ &= (1-\hat p^{B}_{1})^{2} + (0-\hat p^{B}_{2})^{2} \\ &= (1-0.99)^2 + (0-0.01)^2 \\ &= 0.01^2 + 0.01^2 \\ &= 0.0002. \end{align*}

Thus the second prediction receives a much smaller Brier loss, because its probability vector is closer to the one-hot vector for the observed class.

The maximum value \(2\) is attained when the prediction puts all probability on the wrong class.

For the Bayes predictor we split the risk in a similar way as Th. 3.2.1. As the \(k\)th component of \(r(Y)\) is \(\1{Y=k}\), the Brier loss becomes

\begin{align*} \E{\lscr(r(Y), f(X))} = \E{\sum_{k=1}^{K}\rb{\1{Y=k} - f_{k}(X)}^{2}} = \sum_{k=1}^{K} \E{\rb{\1{Y=k} - f_{k}(X)}^{2}}. \end{align*}

To minimize this, we can minimize each of the terms in the summation, which allows us to apply Th. 3.2.1 to each term separately with \(\1{Y=k}\) in the role of \(Y\) for the \(k\)th term. By straight comparision, its conditional expectation is \(\E{\1{Y=k}\given X} = p_{k}(X)\). The conditional variance23An indicator with success probability \(p\) has variance \(p(1-p)\). is \(\V{\1{Y=k}\given X} = p_{k}(X)\rb{1-p_{k}(X)}\). Summing the variances over \(k\) and using that the \(p_{k}(x)\) add up to one,

\begin{align*} \sum_{k=1}^{K} p_{k}(x)\rb{1-p_{k}(x)} = 1 - \sum_{k=1}^{K} p_{k}(x)^{2}. \end{align*}

Summarizing:

Theorem 3.3.1.

For every \(f:\Xset\to\Delta_K\),

\begin{align*} R(f)=\E{\lscr(r(Y), f(X))} &= \underbrace{\E{\sum_{k=1}^{K}\rb{f_{k}(X)-p_{k}(X)}^{2}}}_{\text{squared error}} + \underbrace{\E{1 - \sum_{k=1}^{K} p_{k}(X)^{2}}}_{\text{Gini impurity}}. \end{align*}

From the above and Cor. 3.2.2 we obtain the following corollary.

Corollary 3.3.2.

The minimizer of the Brier loss is the Bayes predictor \(f^{*}=p\), that is

\begin{align*} f^{*}_{k}(x) = p_{k}(x) = \P{Y=k\mid X=x}. \end{align*}

A constant vector as a predictor has the form \(f_c(x)=c \in \Delta_{\Kset}\). As each term \(f_k\) is constant, we can use (3.2.2) term by term. Again, with \(\1{Y=k}\) in the role of \(Y\) for the \(k\)th term, the optimal constant is \(\E{\1{Y=k}} = p_k\) and the variance is \(\V{\1{Y=k}} = p_k(1-p_k)\). Thus the best-in-class predictor and its risk are

\begin{align*} c^{*} &=p, & R(c^{*})&=1-\sum_{k=1}^{K}p_k^2. \end{align*}

Replacing the marginal probabilities by sample frequencies gives

\begin{align*} \hat c^{*}&=\hat p, & \hat R_{\Tset}(c^{*}) &= 1 - \sum_{k=1}^{K} \hat p_{k}^{2}. \tag{3.3.6} \end{align*}

3.3.3 Cross-entropy loss

The cross-entropy loss24Wikipedia: Cross-entropy. arises from the conditional likelihood of the labels. Assuming the labels are independent conditional on their feature vectors, and taking the negative logarithm25Unless a base is shown explicitly, \(\log\) means the natural logarithm throughout these notes. to convert the product into a sum, the average log-likelihood gives

\begin{align*} \frac{1}{n}\log \prod_{i=1}^{n}\prod_{k=1}^{K} p_k(x_i)^{r_{k}(y_{i})} = \frac{1}{n}\sum_{i=1}^{n}\sum_{k=1}^{K} r_{k}(y_{i})\log p_k(x_i) = - \frac{1}{n}\sum_{i=1}^{n}\lscr(r(y_{i}), p(x_i)). \end{align*}

Here the cross-entropy loss is defined as

\begin{align*} \lscr(q, p) = -\sum_{k=1}^{K} q_{k} \log p_k. \tag{3.3.7} \end{align*}

A numerical example shows that cross-entropy loss assigns different losses to predictions with the same most likely class.26In the same as Brier loss. For the example of the Brier loss, here

\begin{align*} \lscr(q,\hat p^{A}) &= -\rb{1\cdot\log \hat p^{A}_{1} + 0\cdot\log \hat p^{A}_{2}} \approx 0.67, \\ \lscr(q,\hat p^{B}) &= -\rb{1\cdot\log \hat p^{B}_{1} + 0\cdot\log \hat p^{B}_{2}} \approx 0.01. \end{align*}

Observe also that as \(0\log 0=0\), a class with zero observed weight, i.e., \(q_k=0\), contributes zero, and by taking \(\log 0 = -\infty\), assigning probability zero to the observed class, i.e., \(q_k=1\), gives infinite loss.

For the Bayes predictor we minimize population risk over all prediction functions.

Theorem 3.3.3.

For every \(f:\Xset\to\Delta_K\),

\begin{equation*} \begin{split} R(f)&=\E{\lscr(r(Y), f(X))}\\ &= \E{\sum_{k=1}^{K} p_{k}(X)\log \frac{p_{k}(X)}{f_{k}(X)}} - \E{\sum_{k=1}^{K} p_{k}(X)\log p_{k}(X)}. \end{split} \tag{3.3.8} \end{equation*}
Proof

Condition on \(X\). Then, as the \(k\)th component of \(r(Y)\) is \(\1{Y=k}\),

\begin{align*} \E{\lscr(r(Y), f(X)) \given X} = -\sum_{k=1}^{K} \E{\1{Y=k\mid X} \log f_{k}(X)} = \sum_{k=1}^{K}\P{Y = k \given X} \log f_{k}(X). \end{align*}

Therefore

\begin{align*} \E{\lscr(r(Y), f(X)) \given X=x} = -\sum_{k=1}^{K} p_{k}(x)\log f_{k}(x). \end{align*}

Now add and subtract \(\sum_{k} p_{k}(X)\log p_{k}(X)\) to get

\begin{align*} -\sum_{k=1}^{K} p_{k}(X)\log f_{k}(X) = \sum_{k=1}^{K} p_{k}(X)\log \frac{p_{k}(X)}{f_{k}(X)} - \sum_{k=1}^{K} p_{k}(X)\log p_{k}(X), \end{align*}

The first term is the relative entropy27Wikipedia: Kullback-Leibler divergence. between \(p(X)\) and \(f(X)\), and the second is the conditional entropy28Wikipedia: Conditional entropy. of \(Y\) given \(X\). The first is non-negative by Gibbs’ inequality29Wikipedia: Gibbs’ inequality. and zero exactly when \(f(X)=p(X)\)

Corollary 3.3.4.

The minimizer of \(\E{\lscr(r(Y),f(X))}\) in (3.1.4) is the Bayes classifier \(f^{*}=p\), that is \( f^{*}_{k}(x) = \P{Y=k\mid X=x}. \)

Constant functions as predictors have the form \(f_c(x)=c\) with \(c\in\Delta_K\). Filling \(c\) into (3.3.8), and using that \(c\) does not depend on \(X\) and that \(\E{p_k(X)}=p_k\), gives the population risk

\begin{align*} R(c) &= \E{\sum_{k=1}^{K} p_{k}(X)\log \frac{p_{k}(X)}{c_{k}}} - \E{\sum_{k=1}^{K} p_{k}(X)\log p_{k}(X)} \\ &= -\sum_{k=1}^{K} p_{k} \log c_{k} \\ &= \sum_{k=1}^{K}p_k\log\frac{p_k}{c_k} -\sum_{k=1}^{K}p_k\log p_k. \end{align*}

The first term in the last line is the relative entropy between \(p\) and \(c\), so by Gibbs’ inequality it is non-negative and vanishes precisely at \(c=p\). Hence the best-in-class predictor returns the marginal class probabilities, and its risk is the entropy of \(Y\):

\begin{align*} c^{*} &= p, & R(c^{*}) &= -\sum_{k=1}^{K}p_k\log p_k. \end{align*}

For the non-empty training list \(\Tset\), replacing \(p_k\) by the class frequency \(\hat p_k\) gives

\begin{align*} \hat c &= (\hat p_{1}, \ldots, \hat p_{K}), & \hat p_{k} &= \frac{|\Tset_{k}|}{|\Tset|}, & \hat R_{\Tset}(\hat c) &=-\sum_{k=1}^{K}\hat p_k\log \hat p_k. \tag{3.3.9} \end{align*}

Affine scores as predictors give logistic regression when fitted with cross-entropy. Taking one intercept \(\beta_{0k}\) and one weight vector \(\beta_{k}\) per class, and writing \(s_{k}(x) = \beta_{0k} + \ip{\beta_{k}, x}\) for the affine scores, let \(\theta\) collect these coefficients. The model class \(\Fset_{\mathrm{softmax}}=\{f_\theta\}\) consists of the rules

\begin{align*} f_{\theta} (x) = \sm(s(x)), \tag{3.3.10} \end{align*}

where the \(k\)th component of the softmax function \(\sm\) is defined as

\begin{align*} \sm_{k}(s) &= \frac{e^{s_{k}}}{\sum_{j=1}^{K} e^{s_{j}}}. \tag{3.3.11} \end{align*}

The softmax functiont maps a vector of real numbers to a probability vector, with larger scores giving larger probabilities.

Filling the softmax rule into (3.3.8) gives its population risk. Since \(\log f_{\theta,k}(x) = s_{k}(x) - \log\sum_{j} e^{s_{j}(x)}\),

\begin{align*} R(f_\theta) &= \E{\log\sum_{j=1}^{K} e^{s_{j}(X)} - \sum_{k=1}^{K} p_{k}(X)\, s_{k}(X)}. \tag{3.3.12} \end{align*}

This model has \(K(p+1)\) parameters: for each of the \(K\) classes one intercept and \(p\) weights for the \(\beta_{k}\). Not all of them can be recovered from data, because an extra factor \(e^{c_{0} + \ip{c, x}}\) cancels between the numerator and the denominator of (3.3.10). Only \((K-1)(p+1)\) parameters are therefore necessary. Two remedies are common: fix one class as a reference by setting its intercept and weight vector to zero, or keep all \(K(p+1)\) of them and let a penalty such as (3.5.1) pick one of the equivalent solutions.

Clearly, there is not a simple method to minimize the risk over the paramaters \(\theta\). In a later chapter we will discuss how to deal with this problem.

With two classes we can express the softmax model in terms of log-odds. Divide the two components of (3.3.10), so that the denominator cancels, and take logarithms,

\begin{align*} \log\frac{\hat p_{2}(x)}{\hat p_{1}(x)} = s_{2}(x) - s_{1}(x) = \beta_{0} + \ip{\beta, x}, \tag{3.3.13} \end{align*}

writing \(\beta_{0} = \beta_{02}-\beta_{01}\) and \(\beta = \beta_{2}-\beta_{1}\). The logarithm of the odds \(\hat p_{2}/\hat p_{1}\) is therefore affine in \(x\), and only the difference of the two score functions is relevant.

3.4 Model flexibility

We have now studied losses and constant or affine rules for regression, nominal classification, and ordinal classification. We next return to regression under squared loss to examine two other ways of constructing a fitted rule. Both aim to approximate the conditional mean \(m(x)=\E{Y\given X=x}\), but they control flexibility differently. Nearest neighbors fit a constant locally; polynomial regression fits a function from a class whose degree we choose.

3.4.1 Nearest neighbors

If several training samples have exactly the feature vector \(x\), we can estimate \(m(x)\) by averaging their outcomes. For continuously distributed features, exact matches to a specified \(x\) generally do not occur. Instead, we can average outcomes at feature vectors near \(x\), using the idea that their conditional means should also be close.

Choose a number of neighbors \(k\), with \(1\leq k\leq n\), and measure closeness by Euclidean distance:

\begin{align*} \norm{x_i-x}_2 =\left(\sum_{j=1}^p (x_i(j)-x(j))^2\right)^{1/2}. \end{align*}

Let \(i_1(x),\ldots,i_n(x)\) be the training indices ordered by increasing distance to \(x\). Break equal-distance ties by the original sample index, so that the first \(k\) indices always identify exactly \(k\) samples, including repeated samples when present. The \(k\)-nearest-neighbor (KNN)30We use lowercase \(k\) for the number of neighbors; uppercase \(K\) continues to denote the number of classes. prediction is

\begin{align*} \hat f_{k,\Tset}(x)=\frac{1}{k}\sum_{a=1}^k y_{i_a(x)}. \tag{3.4.1} \end{align*}

This is precisely the fitted constant of (3.2.3), but fitted to the local list \(\Tset_k(x)=[(x_{i_1(x)},y_{i_1(x)}),\ldots,(x_{i_k(x)},y_{i_k(x)})]\). The list changes with the prediction point. The resulting rule can therefore follow a nonlinear conditional mean even though each individual prediction is obtained by fitting a constant.

\begin{algorithm}
\caption{Predict by averaging the outcomes of exactly \(k\) nearest training samples.}
\begin{algorithmic}
\State \textbf{Input:} a non-empty training list $\Tset$, a feature vector $x$, and an integer $1\leq k\leq|\Tset|$.
\State \textbf{Output:} a numerical prediction at $x$.
\Procedure{KnnPredict}{$\Tset,x,k$}
    \State Order the indices $i_1,\ldots,i_n$ by increasing $\norm{x_i-x}_2$, breaking ties by index.
    \Return $\pr{Average}([y_{i_1},\ldots,y_{i_k}])$
\EndProcedure
\end{algorithmic}

\end{algorithm}

Distances depend on the units of the features. A coordinate measured in euros can dominate one measured in kilometers even if both are useful. One common choice is to center each feature and divide it by its training standard deviation before calculating distances. The same transformation, with the same fitted means and standard deviations, is then applied to new inputs. For \(1\leq j\leq p\), let31We apply the last transformation only when \(\sigma(j)>0\); constant features can be omitted.

\begin{align*} \mu(j)&=\frac{1}{n}\sum_{i=1}^{n}x_i(j),& \sigma(j)&=\sqrt{\frac{1}{n}\sum_{i=1}^{n}(x_i(j)-\mu(j))^2},& \tilde x_i(j)&=\frac{x_i(j)-\mu(j)}{\sigma(j)}. \tag{3.4.2} \end{align*}

A numerical example demonstrates clearly the effect of \(k\). Consider the conditional mean

\begin{align*} m(x)=2-\frac{1}{2}x^2+3x+\sin(4x),\qquad -1\leq x\leq2. \tag{3.4.3} \end{align*}

Generate \(n=200\) independent samples according to

\begin{align*} X_i\sim\operatorname{Unif}(-1,2),\qquad Y_i=m(X_i)+\varepsilon_i,\qquad \varepsilon_i\sim\mathcal N(0,1.5^2), \end{align*}

with the noises independent of the inputs and of one another. Then \(\E{Y_i\given X_i=x}=m(x)\).32Because this is a constructed example, we know \(m\); in an application we only observe the pairs \((x_i,y_i)\).

Fig. 3.1 compares \(k=200,100,50,10,5,1\) on the same sample. At \(k=200\) the rule is constant and cannot follow the trend or the oscillations. At \(k=1\), the fitted rule reproduces each training outcome, including its noise, which is clearly overfitting.

supervised_knn_flexibility.png
Figure 3.1: Nearest-neighbor regression for six values of \(k\), using the same 200 observations in every panel. The green curve is \(m(x)\); the brown curve is the fitted rule. At \(k=200\) the fit is constant. At \(k=1\) it follows individual noisy outcomes.

When the number of features \(p\) is large, e.g. \(p\geq 10\), the nearest neighbors of \(x\) are no longer close to \(x\). Two computations show this for samples that are uniformly distributed on \([0,1]^p\).

First, consider a sub-cube with sidelength33Hence with volume \(a^p\). \(a\) contains a fraction \(s\) of the samples. Then, \(a = s^{1/p}\). For \(s=0.01\) and \(p=10\) this side length is \(0.01^{1/10}\approx 0.63\): a neighborhood that holds 1% of the samples spans 63% of the range of each feature.

Second, let \(X\) and \(X'\) be independent uniform points in \([0,1]^p\). Then

\begin{align*} \E{\norm{X-X'}_2^2} &= \sum_{j=1}^{p}\E{(X(j)-X'(j))^2} = \frac{p}{6}, \tag{3.4.4} \\ \V{\norm{X-X'}_2^2} &= \sum_{j=1}^{p}\V{(X(j)-X'(j))^2} = \frac{7p}{180}, \tag{3.4.5} \end{align*}

where the second line uses that the coordinate differences are independent. The squared coefficient of variation34The variance divided by the squared mean. is

\begin{align*} \frac{\V{\norm{X-X'}_2^2}}{\E{\norm{X-X'}_2^2}^{\,2}} = \frac{7}{5p}. \tag{3.4.6} \end{align*}

Thus, as \(p\) grows, the variation of squared distances relative to their mean becomes small: all points lie roughly equally far away. The \(k\) nearest samples are then barely closer to \(x\) than the other samples, so their average says little more about \(m(x)\) than an average over arbitrary samples. Yet using all \(n\) observations is also undesirable, since it gives the global constant predictor.

This is the curse of dimensionality: local averaging becomes difficult in high dimension. An alternative restricts the rule to a class \(\Fset\) with a fixed number of parameters. All \(n\) samples then contribute to fitting each parameter, not only the \(k\) samples nearest to \(x\).

Polynomial regression is one such class. For a nonnegative integer degree \(q\), define

\begin{align*} \Fset_q =\left\{f_\beta:f_\beta(x)=\beta_0+\sum_{j=1}^q\beta_jx^j,\ \beta\in\R^{q+1}\right\}. \tag{3.4.7} \end{align*}

The cases \(q=0\) and \(q=1\) recover the constant and affine classes for one numerical input. For \(q>1\), the rule is generally nonlinear in \(x\), but remains affine in the transformed features \((x,x^2,\ldots,x^q)\) and linear in the coefficients. Fitting therefore uses the same least-squares method as before:

\begin{align*} \hat\beta\in\argmin_{\beta\in\R^{q+1}} \frac{1}{n}\sum_{i=1}^n \left(y_i-\beta_0-\sum_{j=1}^q\beta_jx_i^j\right)^2. \end{align*}

The coefficients \(\beta\) are parameters: least squares fits them for a given degree. The degree \(q\) is a hyperparameter: it fixes the class \(\Fset_q\) in which we fit.

Fig. 3.2 compares degrees \(q=1,4,10,30\) on the same observations used for KNN. An affine rule, \(q=1\), cannot follow the oscillations in \(m\). A polynomial of degree \(q\) has at most \(q-1\) turning points, so a higher degree can improve the approximation of \(m\), but it also lets the fit respond more strongly to the noise in the sample. The \(q=10\) fit follows \(m\) closely; the \(q=30\) fit adds oscillations, especially near the endpoints.

supervised_polynomial_flexibility.png
Figure 3.2: Polynomial least-squares fits of degrees \(q=1,4,10,30\). The observations are the same as in Fig. 3.1. The degree-one fit misses the nonlinear pattern. The degree-thirty fit shows additional oscillations from fitting noise. Portions of that curve extend beyond the displayed vertical range.

3.5 Regularization

Regularization addresses the problem that a method can be too flexible. When the training outcomes contain noise, a flexible method can adapt not only to stable patterns, but also to accidental variation in the training sample. One way is to restrict the fitted rule deliberately by making \(\Fset\) small; another way is to make complicated rules more expensive in the fitting problem.35Wikipedia: Regularization (mathematics).

Starting from the OLS problem (3.2.4), ridge regression36Wikipedia: Ridge regression. replaces the least-squares criterion by

\begin{align*} \min_{\beta_{0},\beta} \frac{1}{2|\Tset|}\sum_{(x,y)\in\Tset}(\beta_{0} + \ip{\beta, x}-y)^2 +\frac{\lambda}{2}\norm{\beta}_2^2, \qquad \norm{\beta}_2^2 = \sum_j \beta_j^2, \tag{3.5.1} \end{align*}

where \(\lambda\geq0\) is a penalty parameter, or regularization parameter. A larger \(\lambda\) makes large coefficients more expensive. Lasso37Wikipedia: Lasso (statistics). uses the same idea, again starting from (3.2.4), but replaces the squared \(2\)-norm penalty by a \(1\)-norm penalty:

\begin{align*} \min_{\beta_{0},\beta} \frac{1}{2|\Tset|}\sum_{(x,y)\in\Tset}(\beta_{0} + \ip{\beta, x}-y)^2 +\lambda\norm{\beta}_1, \qquad \norm{\beta}_1 = \sum_j |\beta_j|. \end{align*}

These penalties shrink the fitted coefficients and can reduce variance, at the cost of some bias—an instance of the bias-variance tradeoff. The two penalties differ in one important respect: the lasso can set coefficients exactly to zero, so it also performs variable selection in the sense of Section 3.2, while ridge regression only shrinks the coefficients.

Before adding a penalty term, we should standardize each feature using its training mean and standard deviation, as in (3.4.2).

Note that standardization is unnecessary for unregularized OLS: the fitted predictions are unchanged by rescaling a feature. Here, however, it is essential: rescaling changes the coefficient and therefore the penalty applied to it.

3.6 Validation and testing

Above we discussed several predictors and risks. We next discuss methods to assses the quality of the fitting process.

3.6.1 Training, validation, and test data

Choosing and assessing a prediction rule takes three steps. First, we select a function class \(\Fset\) over which we fit. A function in \(\Fset\) is specified by hyperparameters and parameters. For instance, for the union of the polynomial classes (3.4.7), the degree \(q\) is a hyperparameter and the coefficients \(\beta_0,\ldots,\beta_q\) are the parameters. Here we discuss how to tune the hyperparameters and the coeficients and assess how well the final result would do on a new observation \(X\). To tune a hyperparameter, we fix in advance a finite set of values to compare, for instance the degrees \(\Gamma = \set{0,1,\ldots,30}\). Each value in this set is a candidate, and the rule fitted at a candidate is a candidate rule.

For independent observations from a common population, we can randomly divide the available sample into three disjoint lists:

  • The training list \(\Tset\): used to fit candidate rules.
  • The validation list \(\Vset\): used to select a candidate.
  • The test list \(\Eset\): kept aside to assess the final rule after selection and fitting are complete.

Splitting the samples into these subsets affects both fitting accuracy and evaluation precision: more training data can improve a fitted rule, while more evaluation data make its measured risk more precise. There is no single split proportion that is appropriate for every sample size and prediction problem.

Let \(\Gamma\) be a finite collection of candidate settings and let \(\hat f_{\gamma,\Tset}\) be the rule fitted with setting \(\gamma\). Now we use the validation set \(\Vset\) to find the best \(\gamma\). Writing the risk on the validation set as \(\hat R_\Vset(\hat f_{\gamma, \Tset})\),38Note: each candidate is fitted without using the validation observations. the best candidate is

\begin{align*} \hat\gamma\in\argmin_{\gamma\in\Gamma} \hat R_{\Vset}(\hat f_{\gamma,\Tset}). \tag{3.6.1} \end{align*}

After choosing \(\hat\gamma\), we can refit on the concatenated list \( \Dset=\Tset+\Vset. \) The final rule is then \(\hat f_{\hat\gamma,\Dset}\).

Finally, we use the test list to assess the final rule. Its test risk

\begin{align*} \hat R_{\Eset}(\hat f_{\hat\gamma,\Dset}) \end{align*}

is the average loss of \(\hat f_{\hat\gamma,\Dset}\) over the test samples. The test samples are used neither to fit the parameters nor to select \(\hat\gamma\). For the final rule they are therefore new observations, and the test risk estimates its risk \(R(\hat f_{\hat\gamma,\Dset})\) on a new observation \((X,Y)\). Since the test risk is an average of losses on independent samples, a larger test list gives a more precise estimate.

Preprocessing is part of fitting. Means and standard deviations used to scale inputs must be estimated on the training part, then applied unchanged to the validation part. Feature selection, missing-value imputation, and other transformations estimated from data must follow the same procedure. Allowing the validation or test data to influence fitting is called data leakage.

3.6.2 Cross-validation

In the procedure above the candidate rules are fitted on \(\Tset\) only, and \(\Vset\) is never used for this purpose. Cross-validation divides \(\Dset=\Tset+\Vset\) instead into several parts. Each part serves once as validation list, while the rules are fitted on the other parts. Every sample in \(\Dset\) is then used for fitting and for validation, but never both in the same fit.

Let \(N=|\Dset|\), and divide its sample indices into \(F\) disjoint non-empty folds \(\Iset_1,\ldots,\Iset_F\), usually of nearly equal size. For fold \(b\), write

\begin{align*} \Dset_b &=[(x_i,y_i):i\in\Iset_b],& \Dset_{-b} &= \Dset\setminus \Dset_{b} = [(x_i,y_i):i\notin\Iset_b]. \end{align*}

In \(F\)-fold cross-validation, we fit a candiate \(\gamma\) on \(\Dset_{-b}\) and we evaluate its risk on \(\Dset_b\).39Use the same folds for every candidate, so their errors are compared on the same validation observations. Writing \(\hat f_{\gamma,\Dset_{-b}}\) for such a fit, the cross-validation criterion for candidate \(\gamma\) is

\begin{align*} \mathrm{CV}(\gamma) &=\frac{1}{N}\sum_{b=1}^F\sum_{i\in\Iset_b} \lscr(r(y_i),\hat f_{\gamma,\Dset_{-b}}(x_i)) \\ &=\sum_{b=1}^F\frac{|\Dset_b|}{N} \hat R_{\Dset_b}(\hat f_{\gamma,\Dset_{-b}}). \tag{3.6.2} \end{align*}

Every sample contributes one loss, from a rule fitted without that sample’s fold. The weights account for unequal fold sizes. Now select

\begin{align*} \hat\gamma\in\argmin_{\gamma\in\Gamma}\mathrm{CV}(\gamma). \end{align*}

Again, once \(\hat \gamma\) is computed, fit the model on \(\Dset\) for this candidate.

A special case is when \(F=N\); this is called leave-one-out cross-validation: each fit omits just one sample.

\begin{algorithm}
\caption{Select a setting by cross-validation and refit on all development data.}
\begin{algorithmic}
\State \textbf{Input:} a development list $\Dset$, candidate settings $\Gamma$, and $2\leq F\leq|\Dset|$.
\State \textbf{Output:} a selected setting and the final fitted rule.
\Procedure{CrossValidate}{$\Dset,\Gamma,F$}
    \State Divide the indices of $\Dset$ into folds $\Iset_1,\ldots,\Iset_F$.
    \For{$\gamma\in\Gamma$}
        \State $\mathrm{CV}(\gamma)\gets0$
        \For{$b=1,\ldots,F$}
            \State Fit all preprocessing and the rule at $\gamma$ on $\Dset_{-b}$.
            \State $\mathrm{CV}(\gamma)\gets\mathrm{CV}(\gamma)+
            \dfrac{|\Dset_b|}{|\Dset|}\hat R_{\Dset_b}(\hat f_{\gamma,\Dset_{-b}})$
        \EndFor
    \EndFor
    \State $\hat\gamma\gets$ a minimizer of $\mathrm{CV}(\gamma)$ over $\Gamma$
    \State Refit preprocessing and the rule at $\hat\gamma$ on all of $\Dset$.
    \Return $(\hat\gamma,\hat f_{\hat\gamma,\Dset})$
\EndProcedure
\end{algorithmic}

\end{algorithm}

The number of folds \(F\) affects cross-validation in three ways.

First, with equal folds, each fold rule is fitted on \(N(1-1/F)\) samples, while the final rule \(\hat f_{\hat\gamma,\Dset}\) is fitted on all \(N\). A rule fitted on fewer samples has a larger estimation error, so with cross validation we obtain usually less good predictors. Hence \(\mathrm{CV}(\gamma)\) tends to be somewhat larger than the risk of the rule fitted at \(\gamma\) on all of \(\Dset\).

Second, cross-validation fits every candidate \(F\) times, so \(F|\Gamma|\) fits in total, plus the final refit. Hence, CV increases the compuational load.

Third, the random variation of \(\mathrm{CV}(\gamma)\). Whatever \(F\), each sample of \(\Dset\) is validated exactly once, so \(\mathrm{CV}(\gamma)\) is always an average of \(N\) losses. What changes with \(F\) is how much the fold rules have in common. For large \(F\), any two fitting lists \(\Dset_{-b}\) share all but \(2N/F\) samples, so the fold rules are nearly the same rule. If that rule happens to be poor, all its losses are large together, and averaging them removes less of this chance variation than averaging over rules fitted on different samples. Taking \(F=5\) or \(F=10\) keeps the fold training size at 80 or 90 percent of \(N\), with 5 or 10 fits per candidate.

3.7 Assessing a classifier

Classification assessment addresses the problem that classification quality cannot always be summarized by the accuracy on a list \(\Sset\), the fraction of its label predictions that are correct,

\begin{align*} \text{accuracy} = \frac{1}{|\Sset|}\sum_{(x,y)\in \Sset}\1{\hat y(x) = y}. \tag{3.7.1} \end{align*}

In a two-class problem it is customary to call the class of special interest40This is often the rare class, such as a disease in a screening problem. positive and the other class negative. If only \(1\%\) of cases are positive, always predicting the negative class already gives \(99\%\) accuracy, but it misses every positive case. This is the problem of imbalanced data.

For two classes, the four possible outcomes of a prediction are collected in the confusion matrix: a true positive (TP) is a positive case predicted positive, a false positive (FP) is a negative case predicted positive, and true negatives (TN) and false negatives (FN) are defined analogously.

A screening example makes the terminology concrete. In breast-cancer screening, call the screening result positive when the X-ray is suspicious, and negative otherwise. After follow-up, we can compare this screening result with whether cancer was actually present. A true positive is a suspicious X-ray for a woman who has breast cancer; a false positive is a suspicious X-ray where no cancer is found; a false negative is a non-suspicious X-ray for a woman who does have breast cancer; and a true negative is a non-suspicious X-ray where no cancer is found.

In this example, recall is the fraction of women with breast cancer whose X-rays are flagged as suspicious. A test with high recall misses few cancer cases. Precision is the fraction of suspicious X-rays for which breast cancer is actually present. A test with high precision gives few false alarms among the women sent for further tests. The false-positive rate is the fraction of women without breast cancer whose X-rays are nevertheless flagged as suspicious.

A good screening test should have high recall, because missed cancer cases are serious. High precision is also desirable, but it can be hard to achieve when the disease is rare. In practice there is often a tradeoff: flagging more X-rays as suspicious can increase recall, but it may also create more false positives and lower precision.

Counting these outcomes over the evaluation set gives three useful rates. The true-positive rate, or recall,41The name comes from information retrieval: recall measures what fraction of all relevant cases the method retrieves, or ``recalls’’. Here the relevant cases are the positive cases. \(\mathrm{TP}/(\mathrm{TP}+\mathrm{FN})\), is the fraction of positive cases that are found. The false-positive rate, \(\mathrm{FP}/(\mathrm{FP}+\mathrm{TN})\), is the fraction of negative cases that are wrongly flagged. Precision, \(\mathrm{TP}/(\mathrm{TP}+\mathrm{FP})\), is the fraction of predicted positives that are correct. In the example above, always predicting the negative class has recall \(0\): none of the positive cases are found. The accuracy is high only because positive cases are rare.

The always-negative rule is an example of a baseline: a simple reference method, such as always predicting the most frequent class in classification, or the training mean in regression. Reporting the performance of a fitted method alongside a baseline shows whether it improves on this simple reference under the chosen evaluation measure.

3.8 Exercises

Conceptual 1.

The setup of supervised prediction uses three sets, the feature space \(\Xset\), the outcome space \(\Yset\), and the prediction set \(\Aset\), and four functions, the prediction function \(f\), the decision map \(d\), the label-lifting map \(r\), and the loss function \(\lscr\).

  1. For each set, say what it contains and why we introduce it as a separate set. Why is it not enough to take \(\Aset=\Yset\)?
  2. For each function, give its domain and codomain, and explain its role.
  3. Why do we require \(d(r(y))=y\)?
  4. Work out all seven objects for classification with \(K\) classes, where the rule outputs class probabilities and the loss is the Brier loss
  5. Do the same for regression under squared loss.
Solution
  1. \(\Xset\) contains the feature vectors: the information available about a case when we must predict. \(\Yset\) contains the outcomes as they are observed and reported, such as a number or a class label. \(\Aset\) contains the objects the rule may output. If \(\Aset=\Yset\), a classifier can only output a single label. A probability vector in \(\Delta_K\) also states how sure the rule is, and a label cannot carry that. A separate \(\Aset\) allows such outputs.
  2. \(f:\Xset\to\Aset\) is the rule we fit: it maps the features of a case to a prediction. \(d:\Aset\to\Yset\) converts a prediction into the value \(\hat y=d(f(x))\) that we report. \(r:\Yset\to\Aset\) puts an observed outcome into the prediction set, so that it can be compared with \(f(x)\). \(\lscr:\Aset\times\Aset\to\R_+\) assigns the cost \(\lscr(r(y),f(x))\); it states which errors the application considers expensive. Since \(\lscr\) takes two elements of \(\Aset\), we need \(r\) before we can evaluate it.
  3. Suppose the rule predicts the lifted outcome exactly, \(f(x)=r(y)\). Then the reported value is \(d(f(x))=d(r(y))\), and the requirement ensures this equals \(y\). The reverse identity \(r(d(a))=a\) fails in general: after \(d\) has turned a probability vector into a label, the probabilities cannot be recovered.
  4. Classification: for numerical feature vectors, take \(\Xset\subseteq\R^p\). Then \(\Yset=\set{1,\ldots,K}\), \(\Aset=\Delta_K\), and \(f:\Xset\to\Delta_K\) returns the predicted class-probability vector \(f(x)=\hat p\). The decision map is \(d(\hat p)\in\argmax_k \hat p_k\), \(r(y)=q\) with \(q_k=\1{y=k}\), and \(\lscr(q,\hat p)=\sum_{k=1}^{K}(q_k-\hat p_k)^2\). Indeed \(d(r(y))=y\), since the one-hot vector \(q\) has its only nonzero component at \(k=y\).
  5. Regression: for numerical feature vectors, take \(\Xset\subseteq\R^p\). Then \(\Yset=\Aset=\R\), and \(f:\Xset\to\R\) returns a numerical prediction \(f(x)\). The maps \(d\) and \(r\) are the identity, and \(\lscr(y,\hat y)=(y-\hat y)^2/2\). In regression the distinction between \(\Yset\) and \(\Aset\) is not visible; it is needed when the rule outputs a different kind of object than the outcome.

Conceptual 2.

Consider the problem \(\argmin_f \hat R_{\Tset}(f)\), where \(f\) ranges over all functions \(\Xset\to\Aset\). Assume that \(\lscr(a,b)=0\) if and only if \(a=b\).

  1. Suppose the inputs \(x_1,\ldots,x_n\) are distinct. Describe all minimizers. How much computation does it take to find one?
  2. Now suppose several samples share the same input \(x\) but have different outcomes. What do the minimizers look like under squared loss?
  3. Let \(X\) have a continuous distribution. What does a minimizer predict for a new case, and what does its training risk tell us about its population risk?
  4. How does restricting \(f\) to a model class \(\Fset\) change these answers?
Solution
  1. Since \(\lscr\geq0\), the training risk is at least \(0\). Every \(f\) with \(f(x_i)=r(y_i)\) for \(i=1,\ldots,n\) attains \(0\), so it is a minimizer. The values of \(f\) at all other points of \(\Xset\) do not enter \(\hat R_{\Tset}\), so they can be chosen freely: there are infinitely many minimizers. Finding one takes no computation beyond storing the training set.
  2. The training risk splits into one sum per distinct input. For each distinct input \(x\), the value \(f(x)\) minimizes the loss summed over the samples with that input. Under squared loss, this is the average of their outcomes. Values of \(f\) at other points remain free.
  3. With a continuous distribution, \(\P{X\in\set{x_1,\ldots,x_n}}=0\). A new case therefore almost surely has an input outside the training set, where the minimizer’s value was chosen freely. Equal, zero training risks do not imply equal or small population risks.
  4. In a model class, the value at one input constrains the values at others. For example, an affine rule \(f(x)=\beta_0+\ip{\beta,x}\) is fixed on all of \(\Xset\) by \(p+1\) coefficients. Fitting these coefficients to the training samples then also determines the predictions for new inputs. With \(n>p+1\) samples, an affine rule cannot in general pass through every training point, so fitting it generally requires trading off the losses at different samples.

Conceptual 3.

State the definitions of the concepts Bayes predictor, best-in-class predictor, and empirical-risk minimizer and use these definitions to explain the difference between them.

Solution

The three predictors differ along two axes: which risk is minimized, population risk \(R\) or training risk \(\hat R_{\Tset}\), and over which set of functions the minimization ranges, all prediction functions or the model class \(\Fset\).

  • The Bayes predictor \(f^{*}\in\argmin_{f} R(f)\), (3.1.4), minimizes population risk over all prediction functions.
  • The best-in-class predictor \(f_{\Fset}^{*}\in\argmin_{f\in\Fset} R(f)\), (3.1.5), also minimizes population risk, but only over \(\Fset\).
  • The empirical risk minimizer \(f_{\Tset}^{*}\in\argmin_{f\in\Fset} \hat R_{\Tset}(f)\), (3.1.5), replaces population risk by training risk, still restricted to \(\Fset\).

Because \(\Fset\) is only one set of candidate functions among all possible ones, \(R(f_{\Fset}^{*})\ge R(f^{*})\).

Conceptual 4.

Suppose \(\Fset_1\subseteq\Fset_2\). What can be said about their training risk and their population risk after empirical-risk minimization?

Solution

Write \(f^{*}_{\Tset,i}\in\argmin_{f\in\Fset_i}\hat R_{\Tset}(f)\) for the empirical risk minimizer over \(\Fset_i\), \(i=1,2\), (3.1.5). The training risk cannot increase:

\begin{align*} \hat R_{\Tset}(f^*_{\Tset,2}) \leq \hat R_{\Tset}(f^*_{\Tset,1}), \end{align*}

because the larger class contains all candidates in the smaller class. The population risk can nevertheless increase, because the larger class can fit random details of the training set and overfit.

Conceptual 5.

Classification could be fit directly under the zero-one loss (3.3.2), yet the Brier loss (3.3.5) (or cross-entropy) is used during training instead.

  1. For \(y=1\) (so \(q=(1,0)\)), compute the zero-one loss and the Brier loss of \(\hat p^{A}=(0.51,0.49)\) and \(\hat p^{B}=(0.99,0.01)\). Compare the two pairs of results.
  2. Why does the comparison in part 1 make zero-one loss difficult to optimize by gradient-based fitting, while Brier loss does not have this problem?
  3. Both losses lead to the same rule for turning a prediction \(f(x)\) into a class label. Which map does this, and does it depend on the loss used during training?
  4. Why might we also report accuracy or misclassification rate when the classifier was fitted using Brier loss?
Solution
  1. Under zero-one loss both \(\hat p^{A}\) and \(\hat p^{B}\) predict class \(1\), matching \(y=1\), so both receive loss \(0\); zero-one loss cannot separate them. Under Brier loss, \(\lscr(q,\hat p^{A})\approx0.48\) while \(\lscr(q,\hat p^{B})=0.0002\): it rewards \(\hat p^{B}\) for lying much closer to the one-hot vector, even though both predictions give the same label.
  2. Zero-one loss is piecewise constant in \(f\): the label \(d(f(x))\) only changes where two components of \(\hat p\) tie, so nearby predictions almost always leave the loss unchanged, and its derivative is zero (or undefined) almost everywhere. Brier loss is a smooth, quadratic function of \(\hat p\) with nonzero gradient almost everywhere, so it can guide gradient-based fitting toward more confident, better-calibrated predictions, while zero-one loss gives no such signal.
  3. The decision map \(d(\hat p)\in\argmax_{k}\hat p_{k}\), (3.3.1), turns any prediction into a label; it is the same map whether \(f\) was fit under Brier loss, cross-entropy, or, in principle, zero-one loss. Only the objective used during fitting differs; the reported label is always read off by \(\argmax\).
  4. Accuracy and misclassification rate describe how often the reported class label is correct or incorrect, which is easy to interpret. Brier loss also assesses the predicted probabilities. These measures answer different questions, so reporting classification accuracy can complement evaluation under Brier loss.

Conceptual 6.

One in a thousand screened patients carries a certain disease. Consider the predictor that declares every patient healthy.

  1. Compute its accuracy, (3.7.1).
  2. Compute its recall and its false-positive rate.
  3. Why does the accuracy from part 1 not reveal that this predictor is useless for screening?
Solution
  1. The predictor is correct on the \(999\) healthy patients out of every \(1000\), so its accuracy is \(0.999\).
  2. It flags no patient as positive, so it finds none of the sick patients: recall \(\mathrm{TP}/(\mathrm{TP}+\mathrm{FN})=0/1=0\). It also raises no false alarms among the healthy patients, so its false-positive rate \(\mathrm{FP}/(\mathrm{FP}+\mathrm{TN})=0/999=0\).
  3. Accuracy averages correctness over all patients, and healthy patients vastly outnumber sick ones, so the \(999\) correct predictions on healthy patients swamp the complete failure on the single sick patient. Recall looks only at the sick patients and immediately exposes the failure, because it is \(0\) even though accuracy is \(0.999\).

Conceptual 7.

Consider \(10{,}000\) patients, of whom \(10\) have the disease. A predictor flags \(5\) patients as diseased, of whom \(1\) truly has the disease.

  1. Compute this predictor’s precision.
  2. Why is precision alone not enough to judge whether this predictor is useful for screening?
  3. What is a reasonable baseline to compare this predictor against here, and what would that baseline achieve on accuracy, recall, and precision?
Solution
  1. Precision is \(\mathrm{TP}/(\mathrm{TP}+\mathrm{FP})=1/5=0.2\).
  2. Precision describes only the flagged patients. Here, the predictor finds just \(1\) of the \(10\) sick patients, so its recall is \(1/10=0.1\): it misses the other \(9\). Precision must therefore be considered together with recall.
  3. The always-negative rule (declaring every patient healthy) is a natural baseline here, since it always predicts the most frequent class. It reaches accuracy \(0.999\) and recall \(0\), and its precision is undefined, since \(\mathrm{TP}+\mathrm{FP}=0\). Comparing against it shows that the new predictor does find sick patients that the baseline misses entirely, even though its precision of \(0.2\) means \(4\) out of every \(5\) flagged patients undergo follow-up testing unnecessarily.

Conceptual 8.

  1. What is the validation list \(\Vset\) used for?
  2. What is the test list \(\Eset\) used for?
  3. What is lost if \(\Vset\) and \(\Eset\) overlap, or if \(\Eset\) is used to choose between candidate rules?
  4. Should we fit the final rule on \(\Dset=\Tset+\Vset\) before testing it on \(\Eset\)? Explain why or why not.
Solution
  1. The validation list is used to select among candidate rules fitted with different hyperparameter settings, (3.6.1).
  2. The test list is used once, at the very end, to estimate how the chosen rule performs on new data.
  3. If \(\Vset\) and \(\Eset\) overlap, or if \(\Eset\) is used to choose a candidate, this is data leakage: the test risk is no longer an unbiased estimate of performance on new data, because the chosen rule may have been selected for doing well on data that were supposed to be held out.
  4. Yes, usually. After selecting \(\hat\gamma\) using \(\Vset\), refitting on \(\Dset=\Tset+\Vset\) lets the final rule learn from more data. The test list \(\Eset\) must remain untouched until this final evaluation.

Conceptual 9.

kNN regression predicts by averaging the outcomes of the \(k\) training points closest to \(x\). Suppose the training inputs and a new input \(X\) are independent and uniformly distributed on \([0,1]^p\). Keep the training sample size \(n\) and the number of neighbors \(k\) fixed as \(p\) grows. Write \(x\) for the observed value of \(X\).

  1. What happens to the distance between \(x\) and its nearest neighbors as \(p\) grows? Explain your answer heuristically.
  2. Why does this make the kNN prediction less useful in high dimension? Explain your answer heuristically.
Solution
  1. As \(p\) grows, distances increase and become concentrated relative to their mean. With a fixed number of training samples, the nearest neighbors are therefore barely closer than the other samples.
  2. Since the \(k\) nearest points are no longer meaningfully closer to \(x\) than the rest of the sample, averaging their outcomes says little more about \(m(x)\) than averaging over arbitrary points; the local-averaging idea behind kNN breaks down. This is the curse of dimensionality.

Conceptual 10.

In the cross-validation algorithm presented in this chapter, why must the candidate set \(\Gamma\) be finite?

Solution

The algorithm fits and evaluates a rule for every candidate \(\gamma\in\Gamma\). To complete this exhaustive search, \(\Gamma\) must therefore be finite.

Algorithmical 11.

What should replace ??? in the code below? Give code (pseudocode, Python, or R) or a precise conceptual description.

\begin{algorithm}
\begin{algorithmic}
\State \textbf{Input:} a non-empty training list $\Tset$, a feature vector $x$, and an integer $1\leq k\leq|\Tset|$.
\State \textbf{Output:} a numerical prediction at $x$.
\Procedure{KnnPredict}{$\Tset,x,k$}
    \State Order the indices $i_1,\ldots,i_n$ by increasing $\norm{x_i-x}_2$, breaking ties by index.
    \Return ???
\EndProcedure
\end{algorithmic}

\end{algorithm}
Solution

The complete algorithm is in the main text.

Algorithmical 12.

Describe in your own words, or in pseudocode if you prefer, how \(F\)-fold cross-validation selects a candidate setting \(\gamma \in \Gamma\) and produces the final fitted rule.

Solution

Divide the development list \(\Dset=\Tset+\Vset\) into \(F\) roughly equal folds. For each candidate \(\gamma\in\Gamma\) and each fold \(b\), fit the rule at \(\gamma\) on all other folds, \(\Dset_{-b}\), and evaluate its risk on the held-out fold \(\Dset_b\); averaging the held-out losses over all observations gives the cross-validation criterion \(\mathrm{CV}(\gamma)\). Select \(\hat\gamma\) minimizing \(\mathrm{CV}(\gamma)\) over \(\Gamma\), then refit the rule at \(\hat\gamma\) on all of \(\Dset\) to obtain the final rule \(\hat f_{\hat\gamma,\Dset}\).

Technical 13.

Assume \(\E{Y^2}<\infty\), and let \(m(x)=\E{Y\mid X=x}\). Use the identity

\begin{align*} R(f)=\frac{1}{2}\E{(Y-f(X))^2} =\frac{1}{2}\E{\V{Y\mid X}}+\frac{1}{2}\E{(f(X)-m(X))^2} \end{align*}

to derive the Bayes predictor and the Bayes risk. Also express the excess risk of an arbitrary predictor \(f\).

Solution

The decomposition is minimized when \(f(X)=m(X)\). Hence

\begin{align*} f^*(x)=m(x)=\E{Y\mid X=x},\qquad R(f^*)=\frac{1}{2}\E{\V{Y\mid X}}, \end{align*}

and

\begin{align*} R(f)-R(f^*)=\frac{1}{2}\E{(f(X)-m(X))^2}. \end{align*}

Technical 14.

Under squared loss, derive the optimal constant predictor \(c^*\) and its population risk.

Solution

Minimizing \(\E{(Y-c)^2}\) gives

\begin{align*} c^*=\E Y,\qquad R(c^*)=\frac{1}{2}\V Y. \end{align*}

Technical 15.

Under squared loss, why is the minimum population risk over constant predictors equal to \(\frac{1}{2}\V Y\)?

Solution

By (3.2.2), the optimal constant predictor is \(c^*=\E Y\), with risk

\begin{align*} R(c^*)=\frac{1}{2}\E{\V{Y\mid X}}+\frac{1}{2}\E{m(X)^2}-\frac{1}{2}(\E Y)^2, \end{align*}

from expanding \(\E{(m(X)-c)^2}\) at \(c=\E Y\). By Eve’s law (\(\V Y=\E{\V{Y\mid X}}+\V{\E{Y\mid X}}\)), the last two terms combine to \(\V{\E{Y\mid X}}\), giving \(R(c^*)=\frac{1}{2}\E{\V{Y\mid X}}+\frac{1}{2}\V{\E{Y\mid X}}=\frac{1}{2}\V Y\).

Technical 16.

Derive the approximation–estimation decomposition of the excess risk \(R(f^*_{\Tset})-R(f^*)\). Explain why “approximation error” and “estimation error” are appropriate names.

Solution

Add and subtract \(R(f^*_{\Fset})\): \begin{align*} R(f*\Tset)-R(f*) =\underbrace{R(f*\Fset)-R(f*)}\text{approximation error} +\underbrace{R(f*\Tset)-R(f*\Fset)}\text{estimation error}. \end{align*} \(R(f^*_{\Fset})-R(f^*)\) is the increase in risk caused by restricting the search to \(\Fset\): even the best rule in the class need not approximate the Bayes predictor \(f^*\) well, so it is the approximation error. \(R(f^*_{\Tset})-R(f^*_{\Fset})\) arises only because \(f^*_{\Tset}\) optimizes the training risk \(\hat R_{\Tset}\), estimated from the finite sample \(\Tset\), instead of the population risk \(R\); it is the estimation error of using the samples in \(\Tset\) in place of \(F_{X,Y}\).

Technical 17.

Derive the bias–variance decomposition for squared loss using the average prediction \(\bar f(x)=\EE{\Tset}{\hat f_{\Tset}(x)}\).

Solution

The derivation is given in the proof of Th. 3.2.3.

Technical 18.

For binary classification with Brier loss, derive the Bayes predictor and explain what quantity it predicts.

Solution

For each \(k\in\{1,2\}\), the \(k\)th coordinate of \(r(Y)\) is the indicator \(\1{Y=k}\). Conditional on \(X=x\), this is Bernoulli with success probability \(p_k(x)=\P{Y=k\mid X=x}\). Thus, for a candidate predictor \(f(x)\in\Delta_2\), the conditional expected Brier loss is \[ \E{\lscr(r(Y),f(x))\mid X=x} =\sum_{k=1}^{2}\left[p_k(x)(1-p_k(x))+(p_k(x)-f_k(x))^2\right]. \] The first term for each class does not depend on \(f(x)\). The squared terms are minimized by setting \(f_k(x)=p_k(x)\). Since \(p(x)\in\Delta_2\), the Bayes predictor is

\begin{align*} f^*(x)=p(x),\qquad p_k(x)=\Pr(Y=k\mid X=x), \end{align*}

which predicts the conditional probabilities of the two classes given the feature vector \(x\).