Classification Metrics and Decision Thresholds › Formula
Machine Learning from ScratchAll chapters Classification Metrics and Decision Thresholds › FormulaSection view · Sections in this chapter4 / 10 ↓
Reading tools Definitions, links & notes
Choose your expertise level to adjust how many terms are explained. Beginners see more tooltips, experts see fewer to maintain reading flow. Hover over underlined terms for instant definitions.
Article links
Make inline references clickable
A fitted classifier has not yet made a decision. It has assigned each example a score, and those scores induce an ordering. To act on that ordering we choose a cut point in the ranked list and alert on everything above it. That cut point is the threshold, and the formulas below are the vocabulary for describing what happens as the cut moves. We fix notation once and use it throughout. There are examples, each with a feature vector , a true label , and a score produced by some upstream model. The positive class is the event we want to catch: fraud, machine failure, a disease. We adopt the convention that larger scores mean more evidence for the positive class. A library score must be oriented to the selected positive label; for a two-column probability output, use that label's column. A threshold turns scores into labels through the indicator rule
where is the indicator function, equal to 1 when the statement inside the braces is true and 0 otherwise. Read the rule aloud as "predict positive when the score is at least ". The threshold is a single number; sweeping it produces a family of classifiers, and everything in this chapter is a way of describing that family.
Confusion matrices and class prevalence
At any fixed threshold, every example falls into exactly one of four cells. Those cells are not an arbitrary summary: they are the complete cross-tabulation of the true label and the decision. For a fixed sample and threshold, the four counts completely specify the unweighted binary confusion table. They do not retain score ranking, calibration or subgroup-specific behavior. Writing them as indicator sums,
Each term in each sum is 1 exactly when the example belongs to the cell in question and 0 otherwise, so the sum simply counts the examples in that cell. counts true positives, false positives, false negatives, and true negatives, the same four categories that appear under different names in Type I and Type II Errors: a false positive is a Type I error, a false negative a Type II error.
We arrange the four counts into a matrix, with actual class labelling the rows and predicted class labelling the columns:
The convention matters, so we state it: row 1 means the example is truly negative, column 2 means we predicted positive. If we stack the labels into a column vector and the predictions into with , the same four counts are dot products, with denoting the length- vector of ones:
To see why the translation works, we expand the top-right entry: . The product is 1 only when and , which is precisely the definition of a false positive, and it is 0 in the other three cases. A sum over an indicator product has become a single matrix multiplication, which is what lets us compute all four cells at once in vectorized code.
Two row sums are fixed by the data and do not depend on . The number of actual negatives is and the number of actual positives is , with . The prevalence, also called the base rate, is
The column sums move with : is the number of alerts raised, and is the number of examples we let pass.
Prevalence helps explain why low false-positive rates can coexist with low precision. With both classes present, we take recall and false positive rate . The precision, the fraction of alerts that are real, is
where:
- : the precision, the fraction of raised alerts that are real
- : the number of true positives at the chosen threshold
- : the number of false positives at the chosen threshold
Rewriting each count as a rate times its group size, and , and substituting and , gives
where:
- : the recall, the share of actual positives that are flagged
- : the prevalence, the share of examples that are actually positive
- : the false positive rate, the share of actual negatives that are wrongly flagged
- : the total number of examples
Now we put in the numbers. With , a screening problem with one positive in a thousand,
Only 1.6 percent of alerts are real. The same classifier on a population with would deliver . This comparison holds recall and false positive rate fixed while changing prevalence, as under a pure prevalence shift with unchanged class-conditional score distributions. More general population changes can alter those rates too. The precision formula requires a positive alert probability.
Precision, recall, and threshold curves
For positive denominators, the four counts generate the following metrics, each with an operational reading. Precision is the share of alerts that are correct, recall is the share of positives we catch, and the false positive rate is the share of negatives we wrongly flag:
Recall is identical to the true positive rate, , and the true negative rate is the specificity. The harmonic mean of precision and recall is the score,
where:
- : the harmonic mean of precision and recall at threshold
- : the precision at threshold
- : the recall at threshold
Substituting the definitions of and and clearing denominators, when those expressions are defined, gives the equivalent count form
where , , and are evaluated at threshold . The count form also has a denominator condition; reporting a value for a zero denominator requires an explicit convention. The harmonic mean punishes imbalance between the two: if and , the arithmetic mean is 0.55 but . This is why is described as balancing the two, though it does not encode the stated error costs. Because precision depends on prevalence, F1 can depend on prevalence too; maximizing it need not minimize operational cost.
As decreases, the prediction set grows, so and are nondecreasing while and are nonincreasing. Recall and the false positive rate are nonincreasing in ; precision is not monotone, because its numerator and denominator both grow as decreases and either can win.
The threshold curves plot these quantities against itself. They are the most direct picture of the tradeoff, and they are what you would show when you want to know what happens at a particular cut. The ROC and precision-recall curves are different views of the same sweep: instead of plotting against , they plot one metric against another, which erases from the picture and therefore erases the information about which threshold produced each point.
Two bookkeeping conventions matter in practice and are the source of most off-by-one arguments with software. First, at above the largest score no example is predicted positive, so and precision is . For the precision-recall curve, scikit-learn appends a precision-1, recall-0 plotting endpoint. We use that convention here; it is separate from the configurable zero-division behavior of a standalone precision metric. Second, the achievable confusion matrices are indexed by the distinct score values. Two thresholds lying between the same pair of adjacent sorted scores produce identical predictions, so the curve has one point per distinct score, plus the trivial corner. Ties in the scores are handled by moving all tied examples at once.
ROC AUC, average precision, and their limits
Plotting the true positive rate against the false positive rate as sweeps from down to gives the receiver operating characteristic curve, which runs from at the "alert nobody" corner to at the "alert everybody" corner. The area under it is
where:
- : the false positive rate coordinate, running from 0 to 1
- : the true positive rate on the ROC curve at that false positive rate
For a finite sample with both classes present, the area under the linearly connected empirical ROC points is exactly the trapezoid sum
where:
- : the number of non-origin threshold points, one per distinct score group
- : indexes those points from 1 to in order of nondecreasing FPR, with at the origin
- : the false positive rate at threshold point
- : the true positive rate at threshold point
Each term is a trapezoid with width and average height . Vertical segments have zero width.
The empirical trapezoid area also has an exact pair-count interpretation. Compare every positive score with every negative score. A correctly ordered pair contributes 1, an incorrectly ordered pair 0, and a tied pair one half:
Here indexes positives, indexes negatives, and is the number of positive-negative pairs. With distinct scores this is the fraction of correctly ordered pairs. In a tied score group with positives and negatives, the diagonal ROC segment contributes half of the within-group pairs, which explains the half-tie term. The population interpretation is the probability that an independent positive draw outranks an independent negative draw, with half credit for ties. Scores drawn independently of labels from the same distribution in both classes have expected AUC .
For the precision-recall curve we plot precision against recall and summarize with average precision,
where:
- : average precision, the noninterpolated summary used here
- : the number of distinct score groups
- : indexes the groups in order of decreasing score
- : the recall after including the -th group of tied scores, with
- : the precision at that point
- : the recall gained at step , the width of the staircase step
The formula is the area under a staircase: recall increases by at step , and over that sliver of recall we use the precision achieved at the step, . This is the definition used by scikit-learn's average_precision_score.
The trapezoidal area under the precision-recall curve is a different quantity, and the difference is not cosmetic. The trapezoid rule connects consecutive PR points with straight lines. For this finite deterministic threshold sweep, the interior points of a segment between distinct consecutive PR points are not attainable by a threshold; its endpoints are attainable. Whether the line sits above or below the AP staircase depends on the local slope, so the two summaries can differ in either direction. Here we report the noninterpolated average precision used by scikit-learn and name it explicitly. Other PR-area conventions exist, so the interpolation or summation rule should accompany a reported PR-AUC.
Both summaries have limits that decide when they are appropriate.
- ROC AUC is invariant to any strictly increasing transformation of the scores. Replacing by , a strictly increasing sigmoid rescaling, or when every score is positive leaves every threshold sweep unchanged in shape, so the area is identical. The invariance is a statement that AUC measures ranking only.
- Average precision is not invariant to class prevalence. Changing while holding the class-conditional score distributions fixed leaves the ROC curve exactly unchanged, because both axes normalize within their own class, but it can change precision and average precision, because precision mixes the two classes. A change is not guaranteed at every point; perfect separation is a boundary case. The demonstration is in the next section.
- Neither number identifies an operating point. A model with AUC 0.9 can be deployed at a threshold that produces a 40 percent false positive rate or one that produces a 1 percent false positive rate; both are consistent with the same area.
- Neither summary uniquely rewards truthful probability values: a strictly increasing score transformation preserves both ranking summaries. AUC remains 1 after such a distortion of a perfectly separating score. Check calibration separately when the probability scale is needed for a decision.
- The full ROC area can hide behavior in a small operational region. Adding easily ranked negatives changes the comparison population and may increase AUC; it does not establish how a chosen threshold will behave. Report threshold-specific counts alongside the area.
Decision costs and validation-based threshold selection
Suppose a false positive costs and a false negative costs , both in the same units, typically money or hours of your analyst time. We use a model with strictly positive error costs and zero cost for true positives and true negatives. Adding the same action-independent cost per example would shift every rule equally; costs that differ by action or outcome require a corresponding decision model. The empirical expected cost per example at threshold is
where:
- : the observed expected cost per example at threshold (the empirical, sample-based version of the population cost below)
- : the cost of a false positive
- : the cost of a false negative
- : the number of false positives at threshold
- : the number of false negatives at threshold
- : the number of examples in the sample
The factor converts the total cost into cost per example, matching the population expression's per-example scale. For the population version, now let and let FPR and TPR denote population conditional rates, with both classes present. Then
where:
- : the population expected cost per example at threshold
- : the cost of a false positive
- : the cost of a false negative
- : the population prevalence of the positive class
- : the population false positive rate at threshold
- : the population true positive rate at threshold
This expression is linear in the ROC coordinates, so level sets of constant cost are straight lines in the plane. Writing for the coefficient of and for the coefficient of , the cost is
Setting for a fixed budget and solving for gives the line
so the lines have slope
where:
- : the per-example weight on the false positive rate
- : the per-example weight on the false negative rate
- : the cost of a false positive
- : the cost of a false negative
- : the population prevalence of the positive class
The slope assumes . Setting gives . Lower cost favors smaller FPR and larger TPR; among the available threshold points, you choose the one with the smallest stated cost. Increasing false-positive cost favors fewer alerts, toward lower FPR and TPR; increasing false-negative cost favors more alerts, toward higher FPR and TPR. Ties and a discrete curve can leave the selected point unchanged.
When the score is the true conditional event probability, , the optimal threshold has a closed form. Consider a single example with score , the conditional probability of a positive label. If we predict positive, we pay when the label is 0 (probability ) and nothing when it is 1 (probability ), so the expected cost of a positive prediction is . If we predict negative, we pay when the label is 1 and nothing when it is 0, so the expected cost is . We predict positive exactly when the first is no larger than the second:
where is the score, i.e. the conditional probability that the example is positive. Expected total cost is the sum of conditional per-example costs, so minimizing each term yields a minimizing rule. This argument does not require the observed labels to be independent. At equality either action has the same conditional expected cost; our convention predicts positive. Writing for the boundary probability, its posterior odds equal the cost ratio,
With and the threshold is , far below the default 0.5, and the required odds are 1 to 30. Equal error costs give the cutoff 0.5 in this model. Unequal costs give a different algebraic cutoff, although a population with no scores between the two cutoffs can yield identical decisions. Class imbalance alone does not determine the error costs.
The closed form has a precondition that is easy to miss. It requires the stated calibrated-probability assumption for the relevant population; merely lying between 0 and 1 is insufficient. When that assumption is unavailable, we drop the closed form and minimize the empirical cost over the threshold grid directly. This evaluates the available deterministic threshold states without assuming a probability scale. Its validation minimizer is an empirical choice, not a proof that it equals the population Bayes rule. What we lose is the ability to check the answer against a formula, and what we gain is freedom from the calibration assumption.
The selection protocol follows from the fact that is estimated. We need three disjoint roles. The training split fits the model that produces the scores for you to threshold. The validation split selects the threshold, by minimizing over its grid. The test split is touched once, to report the cost of the chosen rule. Selection can make the reported validation minimum optimistic in repeated samples; using test data to choose the threshold contaminates the only honest measurement we have. This is the same discipline as cross-validation, applied to a parameter that happens to be a scalar, and it is the reason hyperparameter search and nested resampling are natural companions to what we build here.
Mathematical Properties
- Monotonicity. For , every prediction made at is also made at , so and . Recall and the false positive rate are therefore nonincreasing in , and the ROC curve is traced monotonically from to .
- Rank invariance. If is strictly increasing, then , so the entire threshold sweep, and hence the ROC curve, AUC, and the PR curve, are unchanged by replacing with .
- AUC as a probability. With continuous scores, for independent draws from the positive and negative classes. The empirical estimate is the Mann-Whitney statistic divided by , which is why AUC and the Wilcoxon rank-sum test are the same computation in different clothing.
- Prevalence effects. Under a pure prevalence shift with the class-conditional score distributions fixed, population ROC coordinates and AUC are unchanged. Precision and average precision can change; this need not happen under perfect separation. More general population changes can alter ROC behavior too.
- bounds. For defined nonnegative precision and recall with , write and . Then the harmonic mean satisfies . The lower bound follows from , so never falls below the smaller of the two inputs, and it never exceeds their arithmetic mean.
- Cost plateaus. Under the inclusive rule, consecutive observed scores give identical predictions for every . Empirical cost is constant on such a plateau. Distinct plateaus may tie for minimum cost, so the set of minimizing thresholds can be a union of intervals. Reporting a representative threshold does not imply its rounded value remains in the same plateau.
- Undefined corners. Precision is when no example is predicted positive, and recall is when the sample contains no positives at all. Both cases need an explicit convention, and the two curves in software differ in whether the corner point is returned.
Comments
Add to the conversation
A question, a correction, or an example from your own work.
No comments yet. Be the first to share your thoughts!