Classification
Corresponding reading
Chapter 8.1 in Agresti and Kateri (2021). However, we will not discuss all of the classification methods introduced there.
So far we have talked about prediction generally, but our examples and loss functions have assumed a continuous outcome \(Y\). But in fact, it is quite common for prediction that we want to predict a categorical outcome, like a disease diagnosis or the identification of an image to a category.
In terms of prediction of categories, our predictions need to be categories. This is unlike our example of logistic regression, where we estimated the continuous probabilities, \(P(Y=1|X)\).
There are two sorts of models for categorical prediction
We could have a \(f(x)\) that directly outputs the categories without explicitly estimating the probabilities i.e. \[f(X)\in \{0,1\}\] There are many such methods, but we will introduce a very simple method of \(k\)-Nearest Neighbors to demonstrate this method.
We can focus on estimating the probability of being in each category, \[p_k(x)=P(Y=k|X=x)\] An example of a method that predicts the probability is logistic regression. However, this doesn’t give us a prediction of \(Y\) directly. A common choice is to say that \(\hat{f}\) is given by the group that has the largest predicted probability, \[\hat{f}(x)=argmax_k \hat{p}_k(x).\] However, we will see other alternatives could also be chosen.
We will go over these two models (logistic and K-nearest neighbors) as examples to illustrate basic principles of classification and how we measure performance in classification.
I am intentionally writing these descriptions in terms of a category \(k\) because while we will focus on just two categories, i.e. \(k\in \{0,1\}\), these principles can all be extended to more than 2 groups.
K-Nearest Neighbors
We are first going to consider an example of the first strategy: direclty estimating a \(\hat{f}(x)\) that gives the category of an observation based on its value \(X\) of predictors.
\(K\) nearest Neighbors (kNN) is a very simple strategy where we decide how to predict the category of an observation with values \(X\) by looking at the predictions in our training that have similar \(X\) values.
Consider the simulated data in Figure 1, where we have training data with either a single predictor variable (left) or two predictor variables (right); the observations are colored either red or blue based on their outcome. We would like to predict the outcome of a new observation, shown as the black star, based on its \(X\).
The idea of kNN is to simply look at the classifications of nearby training data observations to determine the best classification for our new point. Specifically, we choose the \(k\) training observations that are closest to our observation. We can do this for every possible \(X\) and see that this gives a prediction algorithm \(\hat{f},\)
\[\hat{f}(x)=\begin{cases}1 & \frac{1}{k}\sum_{i\in N_k(x)} Y_i>0.5\\ 0 & \frac{1}{k}\sum_{i\in N_k(x)} Y_i\leq 0.5\end{cases}\] where \(N_k(x)\) is the set of the \(k\) training observations whose \(X_i\) are closest to \(x\). Since \(\frac{1}{k}\sum_{i\in N_k(x)} Y_i\) is the proportion of the \(k\) neighbors in group 1, this is just a majority vote of the \(k\) nearest neighbors.
Ultimately a function \(\hat{f}\) that classifies into groups based on predictors \(X_j\) can be thought of as carving the space of \(X\) values into partitions, where each partition is associated with a prediction \(k\).
Choice of \(k\)
Obviously choosing a particular \(k\) for kNN is arbitrary. If we return to our toy data, we can compare the difference if we use \(k=5\) versus \(k=20\) of the closest data points:
For small \(k\), the prediction depends on only a few nearby points; this means the prediction \(\hat{f}\) can change rapidly with \(x\). So smaller \(k\) allow for prediction functions that are more flexible and the possible functions \(\hat{f}\) it can create are more complex. For large \(k\), we average over many points, so the value of \(\hat{f}(x)\) cannot change as rapidly. Thus the \(\hat{f}\) that are created by small \(k\) are smoother functions of \(x\). The number of neighbors \(k\) is a parameter of the prediction algorithm that controls the complexity of the predictor.
0-1 Loss
Notice that I didn’t use a loss function to create my estimator \(\hat{f}\); once I’ve chosen \(k\), my \(\hat{f}\) is defined. This makes it different from the regression strategies we’ve seen, where MLE defines a loss and we choose the best \(\beta\) values that minimize that loss.1
However, there’s no obvious logic to choose \(k\). This is not an uncommon predicament for many modern prediction methods – they do not assume a parametric model for the data, but there is usually a critical parameter (or parameters) needed for the model. And the best parameter varies depending on the data.
We will generally pick this parameter by chosing the one that minimizes our estimate of the generalization error for a particular loss function. Since we are directly predicting the value of \(Y\), a common loss-function to use is 0-1 loss, which simply is an indicator as to whether we misclassified \(Y\), \[l(Y,\hat{Y})= I(Y\neq\hat{Y})=\begin{cases}1& Y\neq\hat{Y}\\0&Y=\hat{Y}\end{cases}\]
Then \[E(l(Y,\hat{f}(X)))=P(Y\neq \hat{f}(X)).\] And we can estimate this quantity on our test data or with cross validation (never on our training data), with \[\bar{err}_{test}=\frac{1}{n_{test}}\sum_{i=1} I(Y\neq\hat{Y}),\] which is just the proportion of our data for which we make an error.
Example 1 (kNN on the spam data) We return to the spam data from the Logistic Regression chapter, where we want to predict whether an email is spam (\(Y=1\)) or not (\(Y=0\)). Now we will use all six variables in the dataset (with the length of the longest string of capital letters on the log scale). We randomly split the data, using 80% of the emails as training data and the other 20% as a test set.
Because kNN finds neighbors based on the distance between observations, variables measured on a larger scale would dominate the distance. So we first standardize each variable, i.e. subtract its mean and divide by its standard deviation (calculated on the training data).
For example, with \(k=10\), the average 0-1 loss on the test set for the spam email data is 0.133. For comparison, simply predicting every email is not spam would have an error of 0.385.
We can then compare the 0-1 loss on our test data for different \(k\).

Like the examples in the last chapter, the training error under-estimates the error for the most complex predictor (\(k=1\)). (The training error with \(k=1\) is not exactly zero because some emails have exactly the same values of all six variables but different values of \(Y\).)
What we have just described here is model selection: choosing among possible models (parameterized by \(k\)). As we already discussed, we will usually rely on cross-validation error for this, rather than requiring a test set. If we have enough data for a test set, we usually reserve it until the very end, after we’ve made all of our choices and have a final model.
Moreover, we can see that the cross-validation error based on the training data, closely follows the test error. This demonstrates that while CV error is the average over different \(\hat{f}\) models – and not the error of any specific one – it can still be helpful in gauging what would be the actual error of a particular \(\hat{f}\).
True Positive Rate and False Positive Rate
Our 0-1 loss is a single number summary of all errors. But just like in hypotheses testing, there are actually different types of mistakes we can make.
Suppose we have a future/unseen observation \((X,Y)\). We can see the possible errors as a 2x2 table, where we compare the possible values of \(Y\) and its prediction \(\hat{Y}=\hat{f}(X)\).
| \(\hat{Y}=0\) | \(\hat{Y}=1\) | |
|---|---|---|
| \(Y=0\) | True Negative | False Positive |
| \(Y=1\) | False Negative | True Positive |
We can consider the probability of a these events with our prediction model \(\hat{f}\).
True Positive Rate (TPR): the probability that we predict an observation to be 1, given that it truly is 1, \[TPR=P(\hat{Y}=1|Y=1)=P(\hat{f}(X)=1|Y=1)\] The TPR is also called the sensitivity or recall of the procedure. The probability of a False Negative is \[P(\hat{Y}=0|Y=1)=1-TPR.\]
TPR is similar to power, and we want it to be large.
False Positive Rate (FPR): the probability that we (incorrectly) predict an observation to be 1, given that it truly is 0, \[FPR=P(\hat{Y}=1|Y=0)=P(\hat{f}(X)=1|Y=0)\] We also can talk about the specificity or the true negative rate (\(TNR\)), which is equal to\(1-FPR\), i.e. \[\text{specificity}=P(\hat{Y}=0|Y=0).\]
FPR is similar to significance level of a test, and we want it to be small. For various historical reasons, we usually either discuss the \(FPR\) (which should be small) or the specificity (which should be large), but the \(TNR\) is less commonly used, even though its equivalent to specificity.
Notice that both of these measures are the probability of classifying \(Y\) to be \(1\) but under different possibilities of what \(Y\) is. This is like power and signifiance level, where both calculate the probability of a rejection, but under different nulls.
Unlike in hypothesis testing, where we only have one realization of a test, in prediction we will actually have outcomes on every one of our observations in our test data, so we can actually estimate these probabilities from our data. We can create the same 2x2 matrix, but now with the totals of each of the categories over all of the \(n_{test}\) observations (often called the confusion matrix):
| \(\hat{Y}=0\) | \(\hat{Y}=1\) | Total | |
|---|---|---|---|
| \(Y=0\) | True Negatives (TN) | False Positives (FP) | \(TN+FP\) |
| \(Y=1\) | False Negatives (FN) | True Positives (TP) | \(FN+TP\) |
Then \[\widehat{TPR}=\frac{TP}{TP+FN},\qquad \widehat{FPR}=\frac{FP}{FP+TN}.\] Both are calculated within a row of the table, i.e. among the observations with the same true value of \(Y\).
Example 2 For the kNN with \(k=10\), we have the following confusion matrix.
Predicted
Truth 0 1
0 537 29
1 93 261
This gives us the following estimates of the TPR and \(1-FPR\):
TPR 1-FPR
0.7372881 0.9487633
The number of neighbors \(k\) also changes the TPR and FPR. Here we plot the estimated TPR and \(1-FPR\) on the test data for different values of \(k\):

Classification with Logistic Regression
We would first note that in logistic regression, we can similarly expand our model to include more than one variable, \[\log \frac{P(Y=1|X=x)}{P(Y=0|X=x)} = \beta_0+\beta_1x_1+\ldots+\beta_p x_p\] or \[P(Y=1|X=x)=\frac{1}{1+e^{-(\beta_0+\beta_1 x_1+\ldots+\beta_p x_p)}}\] We can choose \(\hat\beta_j\) based on MLE estimation, i.e. maximizing the log-likelihood, \(L(\beta_0,\ldots,L_p)\). Again, we cannot do these calculations by hand, but they be derived numerically with the aid of a computer.
This gives us a predicted probability for each group, \(k=0,1\), \[\hat{p}_1(x)=1-\hat{p}_0(x)=\hat{P}(Y=1|X=x)=\frac{1}{1+e^{-(\hat\beta_0+\hat\beta_1 x_1+\ldots+\hat\beta_p x_p)}}\]
We use the same spam data and the same split into 80% training and 20% test data as in Example 1, now fitting a logistic regression with all six variables on the training data.
Call:
glm(formula = binary ~ log.crl.tot + dollar + bang + money +
n000 + make, family = "binomial", data = spamTrain)
Coefficients:
Estimate Std. Error z value Pr(>|z|)
(Intercept) -3.88986 0.17704 -21.971 < 2e-16 ***
log.crl.tot 0.53108 0.03513 15.119 < 2e-16 ***
dollar 7.20819 0.63784 11.301 < 2e-16 ***
bang 1.37565 0.11648 11.810 < 2e-16 ***
money 1.60084 0.23436 6.831 8.45e-12 ***
n000 3.21588 0.42765 7.520 5.48e-14 ***
make -0.07051 0.17921 -0.393 0.694
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
(Dispersion parameter for binomial family taken to be 1)
Null deviance: 4943.6 on 3680 degrees of freedom
Residual deviance: 3099.1 on 3674 degrees of freedom
AIC: 3113.1
Number of Fisher Scoring iterations: 8
Cross-entropy loss
Let’s look at our likelihood for our logistic regression,
\[\begin{aligned} L(\theta) &=\sum_{i=1}^n y_i\log \pi(x_i)+\sum_{i=1}^n(1-y_i)\log(1-\pi(x_i))\\ &=\sum_{i=1}^n I(Y_i=1)\log p_1(x_i)+\sum_{i=1}^nI(Y_i=0)\log p_0(x_i)\\ &=\sum_{i=1}^n\sum_{k}I(Y_i=k)\log p_k(x_i) \end{aligned}.\] We can see finding the MLE as minimizing the average loss, \[\frac{1}{n}\sum_{i=1}^n l(Y_i,p_k(x_i))\] where \[l(Y,p_k(x))=-\sum_{k}I(Y=k)\log p_k(x)\] This is often called cross-entropy loss. Notice that it easily generalizes to any number of categories.
Evaluating Performance
We can use cross-entropy loss to evaluate the performance of our model. Specifically, we could evaluate this quantity on our test data,
\[-\frac{1}{n_{test}}\sum_{i=1}^{n_{test}} \left(I(Y_i=1)\log \hat{p}_1(X_i)+I(Y_i=0)\log \hat{p}_0(X_i)\right)\]
If we evaluate the cross-entropy loss on the test data using its estimated probabilities \(\hat{p}_1(x)\) (and \(\hat{p}_0(x)=1-\hat{p}_1(x)\)). For comparison, we also calculate it for the logistic regression from the Logistic Regression chapter that uses only the length of the longest string of capital letters, and for the simple prediction that gives every email the same probability of being spam (the proportion of spam in the training data):
| Model | Cross-entropy loss (test data) |
|---|---|
| All six variables | 0.400 |
| Capital letters only | 0.572 |
| Same probability for every email | 0.667 |
Smaller values are better; the model with all six variables has the smallest cross-entropy loss on the test data.
We will often use cross-entropy loss to evaluate different possible models.
Classifications and evaluation
To make a prediction, we need to choose how to convert our \(p_k(x)\) into classifications. Above we said we could just pick the group that has the largest value of \(\hat{p}_k(x)\), \[\hat{f}(x)=argmax_k \hat{p}_k(x).\] Equivalently, we can choose a particular cutoff \(c\), \[\hat{Y}=\hat{f}(x)=\begin{cases}1 & \hat{p}_1(x)>c\\ 0 & \hat{p}_1(x)\leq c\end{cases}\hspace{2ex},\] and the choice \(c=0.5\) corresponds to choosing the group with the largest predicted probability.
Evaluating Classification
If we are converting our predicted probabilities into classifications, then it also makes sense to consider the 0-1 loss to measure how our actual classifications perform.
If we return to the spam data, we use the estimated \(\hat{p}_1(x)\) from our fitted model, and then classify each email using the cutoff \(c=0.5\). This gives the following confusion matrix on the test data:
| \(\hat{Y}=0\) | \(\hat{Y}=1\) | Total | |
|---|---|---|---|
| \(Y=0\) (not spam) | TN = 530 | FP = 36 | 566 |
| \(Y=1\) (spam) | FN = 123 | TP = 231 | 354 |
This gives an average 0-1 loss (proportion misclassified) of \[\frac{FP+FN}{n_{test}}=\frac{36 + 123}{920}=0.173\] and estimates of TPR and FPR of \[\begin{aligned} \widehat{TPR}&=\frac{TP}{TP+FN}=\frac{231}{354}=0.653\\ \widehat{FPR}&=\frac{FP}{FP+TN}=\frac{36}{566}=0.064 \end{aligned}\] For comparison, kNN with \(k=10\) had a 0-1 loss of 0.133, with \(\widehat{TPR}=\) 0.737 and \(\widehat{FPR}=\) 0.051. We can summarize these results in a table:
| Method | 0-1 loss | \(\widehat{TPR}\) | \(\widehat{FPR}\) |
|---|---|---|---|
| Logistic regression (c = 0.5) | 0.173 | 0.653 | 0.064 |
| kNN (k = 10) | 0.133 | 0.737 | 0.051 |
Comparing possible cutoffs with ROC Curves
While a cutoff of 0.5 is perfectly reasonable, we could instead choose any \(c\) between 0 and 1. Making \(c\) smaller means we predict \(\hat{Y}=1\) for more observations; thus we will correctly catch more of the true \(Y=1\) observations, but we will also incorrectly call more of the \(Y=0\) observations a 1. This will be a tradeoff between TPR and FPR. This is similar to choosing our signifiance level in hypothesis testing; we are making a tradeoff.
This tradeoff can be very important in deploying a classification, where classifications have real world meaning. A high TPR means we catch most spams. But a high FPR means that real emails that we presumably want to read are classified and junk and we may never see them. I might decide that losing 6% of my emails is not okay. Raising my \(c\) would call fewer emails spam (and clog up my inbox), but result in me losing fewer emails.
A ROC curve (Receiver Operating Characteristic curve) is a plot that evaluates this tradeoff by plotting the TPR against the FPR for all possible cutoffs \(c\).2

As the cutoff \(c\) decreases, we move up and to the right along the curve: we catch more of the spam emails (higher TPR), at the cost of labeling more of the good emails as spam (higher FPR).
Exercise/Question
Notice that the ROC curve is a non-decreasing function. Why is this always true?
Comparing Models
We can also use ROC curves to compare models. A perfect classifier would reach the top left corner, \((0,1)\), while a classifier that just guesses at random will fall along the diagonal line, \(y=x\).
In our above ROC curve, we also plotted the ROC of a model that used only one variable, the length of the longest string of capital letters (also fit on the same training data). The model with all six variables has a curve that is closer to the top left corner than the model with just one variable, meaning for any given FPR it has a higher TPR. This means the model using all six variables has uniformly better performance.3
When we are comparing many models, the ROC curve can often be summarized by the area under the curve (AUC). This allows for a numerical comparison of these plots. A higher AUC does not mean that it gives uniformly better results across all values of FPR, however; you have to inspect the curves to know that. Our baseline for comparison of AUC is \(AUC=1/2\) since this is the value of the AUC for random guessing (ROC curve \(y=x\)).4
| Model | AUC |
|---|---|
| All six variables | 0.897 |
| Capital letters only | 0.751 |
Population Versions of AUC/ROC
The previous definition of AUC and ROC are actually the versions calculated on our data. We didn’t write them as \(\hat{AUC}\) and \(\hat{ROC}\) for simplicity, but in fact they are estimating the true, unknown relationships between the true (unknown) TPR and FPR – the conditional probabilities \[ \begin{gathered} TPR(c)= P(\hat{p}_1(X)>c | Y=1)\\ FPR(c)=P(\hat{p}_1(X)>c | Y=0). \end{gathered}\]
In the same vein, the true unknown AUC is an integral. If we write \(T(f)\) as the function that takes a given FPR of \(f\) and provides the TPR, then \[AUC=\int_0^1 T(f)\; df.\]
The AUC as a Probability
The AUC can also be shown to be the probability that a randomly chosen observation with \(Y=1\), call it \((X_1,Y_1)\), gets a higher value of \(\hat{p}_1\) from our classifier than another independent and randomly chosen observation that has \(Y=0\), call it \((X_0,Y_0)\). \[AUC=P(\hat{p}_1(X_1)>\hat{p}_1(X_0)).\] Thus, if the \(AUC=1/2\), a randomly chosen observation with \(Y=1\) is equally likely to get a higher or a lower score than a randomly chosen observation with \(Y=0\).
Proof. Let \[\begin{aligned} S_1=\hat{p}_1(X_1) | Y_1=1\\ S_0=\hat{p}_1(X_0) | Y_0=0 \end{aligned}\] be the predicted probabilities of the two random observations considered above, random observations with \((X_1,Y=1)\) and \((X_0,Y=0)\). Then \[\begin{aligned} TPR(c)=P(S_1>c)=P(\hat{p}_1(X_1)>c | Y_1=1)\\ FPR(c)=P(S_0>c)=P(\hat{p}_1(X_0)>c | Y_0=0) \end{aligned}\] This means that \[TPR(c)=1-F_1(c),\] where \(F_1\) is the cdf of \(S_1\), and similarly, \[FPR(c)=1-F_0(c),\] where \(F_0\) is the cdf of \(S_0\). We’ll assume that \(S_1\) and \(S_0\) are continuous with densities \(f_1\) and \(f_0\), and that \(F_0\) is strictly increasing (so that it can be inverted).
We want to show that
\[\int_0^1 T(f)\; df =P(S_1>S_0).\] To do this, we want to convert our integral into quantities that involve our random variables \(S_1\) and \(S_0\). We do this by noting that if we know our \(FPR(c)=f\), then we can determine the \(c\) that created this FPR, by inverting the following equation \[FPR(c)=1-F_0(c)\] which gives us that \(c=F_0^{-1}(1-f)\) for any given FPR value \(f\).
\[\begin{aligned} \int_0^1 T(f)\; df &= \int_0^1 P(S_1>F_0^{-1}(1-f))\; df\\ & \text{change of variable: }c=F_0^{-1}(1-f); -f_0(c) dc=df\\ &=-\int_{+\infty}^{-\infty}P(S_1>c)f_0(c) dc \\ &\text{because as } c\rightarrow \infty, FPR\rightarrow 0\\ &=\int_{-\infty}^{+\infty}P(S_1>c)f_0(c) dc \\ \end{aligned}\]
Looking at the other side of our equation, by the law of total probability we can condition the probability \(P(S_1>S_0)\) on the value of \(S_0\), as follows: \[\begin{aligned} P(S_1>S_0)&=\int_{-\infty}^{\infty} P(S_1>c\,|\,S_0=c)\,f_0(c)\,dc\\ &=\int_{-\infty}^{\infty} P(S_1>c)\,f_0(c)\,dc\\ &=AUC \end{aligned}\] where we can drop the conditioning on \(S_0\) because \(S_1\) and \(S_0\) are independent.
The AUC and the Wilcoxon Rank-Sum Test*
The AUC actually is closely related to doing a Wilcoxon rank-sum test (or Mann-Whitney) hypothesis test. Specifically, the AUC is a rescaled version of the test statistic of a rank-sum test comparing the predicted probabilities \(\hat{p}_1(X)\) of the observations with \(Y=1\) to those of the observations with \(Y=0\).
In otherwords, if we take the values of our predicted probabilities on our observed data, \[\hat{p}_i=\hat{p}_1(X_i)\] and put our observations into groups based on whether \(Y_i=0\) or \(Y_i=1\), then the Mann-Whitney form of the test statistic for the Wilcoxon rank-sum test using \(\hat{p}_i\) as our data will be \(U=n_0n_1\cdot AUC\).
This points out that in fact, the ROC curve doesn’t actually depend on the value of the \(\hat{p}_i\) but only the rank of these predicted probabilities. Any transformation of the \(\hat{p}_i\) that preserves the rank will result in the same ROC curve. This is because we are going through all possible cutoffs \(c\) to make the \(\hat{TPR}\) and \(\hat{FPR}\) calculations, so we will eventually get the points in the ROC curve.
Moreover, the rank-sum test can be summarized as asking whether the distributions of two populations are the same (the null hypothesis), or whether one population tends to yield larger values. We’ve just seen that the AUC measures the probability that one group yields bigger predicted probabilities than the other. So it makes sense that the \(AUC\) would be closely related to the statistic that we use to test the rank-sum null hypothesis.
Proof. In practice we estimate the ROC curve from our test data, where we have \(n_1\) observations with \(Y=1\) and \(n_0\) observations with \(Y=0\), with scores \(\hat{p}_i=\hat{p}_1(X_i)\). Our estimated ROC curve uses \(\widehat{TPR}(c)\) and \(\widehat{FPR}(c)\), which is the same as replacing \(F_1\) and \(F_0\) above with the empirical cdfs of the scores in each group. Doing the same calculation with the empirical distributions turns the integral into an average over the observations with \(Y=0\), and \(P(S_1>S_0)\) into the proportion of all \(n_1n_0\) pairs of observations (one with \(Y=1\), one with \(Y=0\)) where the observation with \(Y=1\) has the higher score: \[\widehat{AUC}=\frac{1}{n_0}\sum_{j:Y_j=0}\widehat{TPR}(\hat{p}_j)=\frac{1}{n_1n_0}\sum_{i:Y_i=1}\sum_{j:Y_j=0}I(\hat{p}_i>\hat{p}_j)\] (this assumes there are no ties; if there are ties, \(\hat{p}_i=\hat{p}_j\), the area under the estimated ROC curve counts each tied pair as \(\frac{1}{2}\), as in \(U\) below). The double sum \[U=\sum_{i:Y_i=1}\sum_{j:Y_j=0}\left[I(\hat{p}_i>\hat{p}_j)+\frac{1}{2}I(\hat{p}_i=\hat{p}_j)\right]\] is the Mann-Whitney statistic for comparing the scores of the two groups, and it is equivalent to the Wilcoxon rank-sum statistic. If we rank all \(n_1+n_0\) scores together, the rank of an observation with \(Y=1\) is 1 plus the number of observations with a smaller score. Adding these up over the \(n_1\) observations with \(Y=1\) to get their rank sum \(W_1\), the observations with \(Y=0\) that have smaller scores contribute \(U\) in total, and the other observations with \(Y=1\) that have smaller scores contribute \(0+1+\ldots+(n_1-1)\), so \[W_1=n_1+U+\frac{n_1(n_1-1)}{2}=U+\frac{n_1(n_1+1)}{2}.\] Putting these together, \[\widehat{AUC}=\frac{U}{n_1n_0}=\frac{W_1-\frac{n_1(n_1+1)}{2}}{n_1n_0}.\] So the estimated AUC is just the rank-sum statistic of the scores of the \(Y=1\) group, shifted and scaled to be between 0 and 1.
Example 3 (AUC of the spam classifiers) We can calculate the AUC of our two logistic regression models on the spam test data using the rank sum, and compare it to the area under the ROC curves we plotted above (calculated with the trapezoid rule) and the Mann-Whitney statistic \(U\) that is reported by R’s wilcox.test function (which R calls W).
| Model | \(U\) (wilcox.test) | \(U/(n_1n_0)\) | AUC from rank sum | Area under ROC curve | Wilcoxon p-value |
|---|---|---|---|---|---|
| All six variables | 179702.0 | 0.8969 | 0.8969 | 0.8969 | <2e-16 |
| Capital letters only | 150478.5 | 0.7510 | 0.7510 | 0.7510 | <2e-16 |
The AUC from the rank sum and \(U/(n_1n_0)\) agree exactly, and the area under the plotted ROC curve agrees up to the small error from only evaluating the curve at a grid of cutoffs. The model with all six variables has an AUC of 0.897: for 90% of the pairs of a spam and a non-spam email in the test data, the spam email has the higher predicted probability of being spam. The Wilcoxon p-values show that both models are clearly better than random guessing (\(AUC=\frac{1}{2}\)).
Other measures of error rates
There are other measures and measurement curves that are based on different quantities than TPR and FPR (or work in combination with them).
Precision
One of the most relevant measurements is the precision or positive predictive value (PPV) of our classifier.
TPR and FPR condition on the true value of \(Y\). We can instead condition on our prediction, and ask: of the observations that we predicted to be 1, what proportion truly are 1? This is the precision of our classifier, \[\text{precision}=P(Y=1|\hat{Y}=1)=P(Y=1|\hat{f}(X)=1).\] We estimate it from a column of the confusion matrix, rather than a row, \[\widehat{\text{precision}}=\frac{TP}{TP+FP}.\]
Relationship to Prevalence in Population
An important difference between precision and the TPR/FPR is that precision depends on how common \(Y=1\) is in our population. The TPR and FPR are properties of the classifier alone: they condition on \(Y\), so they don’t depend on how many observations have \(Y=1\) versus \(Y=0\).
Let \(\pi=P(Y=1)\) be the proportion of the population with \(Y=1\) (often called the prevalence). Then by Bayes’ rule, \[\begin{aligned} \text{precision}&=\frac{P(\hat{Y}=1|Y=1)P(Y=1)}{P(\hat{Y}=1|Y=1)P(Y=1)+P(\hat{Y}=1|Y=0)P(Y=0)}\\ &=\frac{TPR\cdot\pi}{TPR\cdot\pi+FPR\cdot(1-\pi)}. \end{aligned}\] Precision combines TPR and FPR with \(\pi\), so the same classifier, with the same TPR and FPR, can have very different precision depending on how rare \(Y=1\) is. If \(Y=1\) is rare (\(\pi\) small), even a small FPR can mean that most of the observations we predict to be 1 are false positives, simply because there are so many more observations with \(Y=0\). Think of a diagnostic test for a rare disease: even a very accurate test can produce mostly false positives, simply because there are not that many times that a positive will be tested to begin with.
This also means that our estimate of precision from test data is only a good estimate of the precision we would see in practice if the proportion of \(Y=1\) in our test data is similar to the proportion in the population where we will use the classifier. Alternatively, if we know the prevelance in our population (e.g. we know the prevalence of a disease in our population), we could use this known value to estimate the precision/PPV based on our estimates, \(\widehat{TPR}\) and \(\widehat{FPR}\).
Example 4 For the kNN with \(k=10\) in Example 2, 290 of the test emails were predicted to be spam, and 261 of those truly were spam, so \[\widehat{\text{precision}}=\frac{261}{290}=0.9.\] We get the same number (up to rounding) by plugging \(\widehat{TPR}=0.737\), \(\widehat{FPR}=0.051\), and the proportion of spam in the test data, \(\hat{\pi}=0.385\), into the Bayes’ rule formula above.
Precision-Recall Curves
Precision is usually paired with the TPR, which in this context is usually called the recall: recall is the proportion of the true 1’s that we find, and precision is the proportion of the observations we call 1 that are correct.
Just as with the TPR and FPR, the precision and recall of a classifier depend on the cutoff \(c\) we use to turn \(\hat{p}_1(x)\) into a classification. A precision-recall curve (PR curve) plots the precision against the recall (TPR) for all possible cutoffs \(c\). As \(c\) decreases we predict more observations to be 1, so the recall goes up, and the precision will generally go down. Unlike the ROC curve, however, the PR curve does not have to be monotone: lowering the cutoff can add a group of observations that are mostly true 1’s, which increases the precision.
The baselines are also different. A perfect classifier reaches the top right corner, \((1,1)\), i.e. it finds all of the 1’s without any false positives. A classifier that guesses at random has a precision equal to \(\pi\) for every cutoff, so the random-guessing baseline is a horizontal line at the prevalence \(\pi\), rather than the diagonal line of the ROC curve. Just as for the ROC curve, the PR curve is sometimes summarized by the area under it, though unlike the AUC, this area doesn’t have a simple probability interpretation, and it depends on \(\pi\).
PR curves are most useful when \(Y=1\) is rare and what we care about is how trustworthy our predictions of \(\hat{Y}=1\) are, e.g. screening for a rare disease or flagging fraudulent transactions. In that case the ROC curve can look very good, because the FPR divides the number of false positives by the (large) number of observations with \(Y=0\), even when the false positives far outnumber the true positives.
Example 5 (Precision and recall with rare spam) In our spam test data, 38% of the emails are spam, so spam is not very rare. To see what happens when spam is rare, we create a new test set by keeping all of the non-spam emails in our test data, and randomly sampling only enough of the spam emails so that spam makes up 5% of this new test set. We do not refit the model: we use the same logistic regression with all six variables, fit on the same training data, and only change which test emails we evaluate it on.
nonSpam spam
566 30

The two ROC curves are estimates of the same ROC curve, since sampling the test emails based on whether they are spam doesn’t change the TPR or FPR. They differ only because the subsample has just 30 spam emails, so its TPR is estimated less precisely and its ROC curve is more jagged. The PR curves, on the other hand, are very different: for the same recall, the precision is much lower when spam is rare.
We can see this in the precision at the cutoff \(c=0.5\):
| Test data | Proportion spam | \(\widehat{TPR}\) | \(\widehat{FPR}\) | Precision | Precision from Bayes’ rule |
|---|---|---|---|---|---|
| Full test data | 0.385 | 0.653 | 0.064 | 0.865 | 0.865 |
| Test data with 5% spam | 0.050 | 0.667 | 0.064 | 0.357 | 0.352 |
\(\widehat{TPR}\) and \(\widehat{FPR}\) are about the same in the two test sets, but the precision drops from 0.87 to 0.36. With 5% spam, most of the emails that we send to the spam folder are actually real emails, even though we only send 6% of the real emails there. This is what Bayes’ rule predicts from \(\widehat{TPR}\) and \(\widehat{FPR}\) of the full test data (last column of the table); the small difference is because the TPR of the subsample is estimated from only 30 spam emails.
Which measures to use?
It can seem a little strange that we pair together Precision (calculated conditional on \(\hat{Y}=1\)) with Recall/TPR (calculated conditional on \(Y=1\)). Especially since ROC curves pair together FPR/TPR (calculated condition on \(Y=0\) and \(Y=1\)).
There is a measure that “matches” precision, called the negative predicitive value (NPV), \[NPV=P(Y=0|\hat{Y}=0)=P(Y=0|\hat{f}(X)=0).\] and we estimate it from the other column of the confusion matrix, not used by precision/PPV: \[\widehat{NPV}=\frac{TN}{TN+FN}.\] It has similar properties of as precision/PPV, in the sense of being dependent on the prevalence of the population. \[NPV=\frac{(1-FPR)(1-\pi)}{(1-FPR)(1-\pi)+(1-TPR)\,\pi}.\] Precision/PPV and NPV are reported together in medical contexts, like in evaluating diagnostic procedures, and are similarly important in evaluating the effect of the classifier with unbalanced prevalance.
When use Precision-Recall versus ROC curves?
Which makes the most sense depends on the context and the prevalence of \(Y=1\) outcomes in your application. Historically in machine learning contexts, a classifier was frequently trying to identify something quite rare from a large pool. Think of a search algorithm, where the user will be searching a collection of a million documents, and 20 of them are relevant.
- True Negatives (TN): The negatives are huge and uninteresting. The true negatives are the roughly one million irrelevant documents you correctly didn’t return. The measures that use TN are FPR/Specificity, NPV, and overall error/accuracy. With TN so large, these are close to 1 no matter what model you use, and thus can’t distinguish between classifiers.
- Precision and recall are the two natural measures that never use TN. Precision is \(TP/(TP+FP)\), and recall is \(TP/(TP+FN)\). Together they pin down TP, FP and FN up to scale, which is everything in the table except TN. They answer the user’s two questions: “how much of what I got is useful?” and “how much of what’s useful did I get?”
For this reason, NPV is not frequently considered in machine learning contexts, and ROC curves are less common. But precision-recall curves will be less relevant in situations with less lopsided prevalence values.
| Pair of measures | Conditions on | Common in |
|---|---|---|
| TPR (sensitivity) and FPR (or sensitivity, \(1-FPR\)) | the truth, \(Y\) (rows of the confusion matrix) | medicine, statistics |
| Precision/PPV and NPV | the prediction, \(\hat{Y}\) (columns) | medicine |
| Precision and recall/TPR | one column and one row, both about the positives | information retrieval, machine learning |
References
Footnotes
We have discussed varying the number of predictor variables in multiple regression, but that is distinct from the point here. With kNN, even with a fixed set of predictors, I don’t have a strategy for picking \(k\); if I also consider which variables to use for kNN that’s just yet another parameter.↩︎
In practice, we make a large grid of \(c\) values.↩︎
Technically, when the two curves start plateauing at around \(\widehat{FPR}>0.8\), the curves do cross slightly.↩︎
Though you can get an \(AUC=1/2\) for other curves as well; it’s not a unique property of \(y=x\).↩︎