Evaluation metrics: thresholds, rankings and costs
Organize metrics by what they measure: threshold-based decisions (confusion matrix, precision, recall, F1), threshold-independent ranking quality (ROC, AUC, precision-recall curves), and regression errors. Derive the optimal threshold from a cost matrix and address class imbalance using weights, resampling and prior correction. Probability metrics (log-loss, Brier) are covered in depth in the calibration lessons.
After this lesson you can
- Compute the confusion matrix and derived metrics, including macro, micro and weighted averages.
- Construct an ROC curve and prove that AUC is the probability that a positive scores above a negative.
- Choose between ROC and precision-recall according to prevalence and explain why PR is more informative for rare classes.
- Derive the optimal decision threshold for a probabilistic classifier from a cost matrix.
- Address imbalance with class weights, resampling and prior correction, and measure their effects.
- Choose regression metrics consistent with the loss and recognize their pathologies.
Before you start
Motivation: 99% accuracy that detects nothing
You have an analyzer scoring each function in a repository by its risk of containing a vulnerability, and an evaluation set of 10,000 manually reviewed functions, of which 100 are vulnerable: a prevalence of 1%. Compare two models.
- The lazy model always says “not vulnerable.” It is correct in 9900 of 10,000 cases: accuracy . It finds no vulnerabilities.
- A real model detects 80% of vulnerable functions (80 of 100) and falsely raises the alarm on 2% of healthy ones (198 of 9900). It is correct in cases: accuracy , worse than the lazy model. Of its alerts, only 28.8% are real vulnerabilities.
By accuracy the lazy model wins. By recall (how many vulnerable functions you find), the real model wins decisively. By precision (how many alerts are true), the real model is mediocre: over seven in ten requested reviews are wasted. None of these figures is wrong. They answer different questions, and choosing the wrong question is the most common way to mislead yourself when evaluating a model.
This lesson organizes metrics by what they measure:
- Decisions at a threshold. Once the threshold is fixed, the model is a hard classifier and everything is summarized by a confusion matrix: precision, recall, specificity, and their multiclass averages.
- Ranking quality, without a threshold: the ROC curve, its area (which turns out to be a probability of ordering a pair correctly), and the precision-recall curve, which responds to prevalence when ROC does not.
- Decisions with costs. If a false negative costs fifty times more than a false positive, the threshold is not a knob adjusted by eye: it follows from a calculation, provided probabilities mean what they say.
- Class imbalance, using weights, resampling and probability correction, measured in a lab with 1% positives.
- Regression errors: which prediction each metric rewards, continuing the regression losses and functionals elicited by each loss from the module’s first lesson.
Probability metrics (log-loss, Brier) and calibration have their own later lessons; here they appear only where needed.
Threshold decisions: the confusion matrix
Most probabilistic classifiers, such as logistic regression, return a score rather than a class (a probability, logit, or distance to the hyperplane). To decide, set a threshold and predict
In an evaluation set with positives and negatives, each example falls into one of four cells.
The right-hand column matters. Recall, specificity and FPR are conditioned on the true class: they describe how the model treats positives and negatives separately and do not change when their relative numbers change. Precision is conditioned on the prediction, and by Bayes’ theorem, with prevalence ,
The same recall and FPR give very different precision depending on : in the opening example, and give with , and with . Accuracy also depends on , because averages the two rates weighted by prevalence: with , specificity weighs 99 times more than recall. That is what hurt the real model against the lazy one. Balanced accuracy, , removes that weighting.
combines precision and recall with the harmonic mean, , which stays close to the smaller value: with and it gives , not the arithmetic mean’s . Notice does not appear: adding a million correctly classified negatives does not change . That is useful when negatives are “everything else” (healthy functions, irrelevant pages), and a drawback when they matter. The parameter of has a precise meaning, going back to van Rijsbergen’s effectiveness measure in information retrieval: differentiation gives exactly when . With , while recall is less than twice precision, a point of recall raises more than a point of precision; is common when a false negative is serious (screening, security), and when false alarms are serious.
The interactive illustrates the idea organizing the rest of the lesson: a threshold metric evaluates one point; curves evaluate every point the model can reach. If the threshold is not yet decided (because it depends on costs, review capacity, or production prevalence), single-point metrics conflate the model with one possible configuration.
Multiclass: macro, micro and weighted
With classes, the confusion matrix is where counts examples of true class predicted as (rows: truth; columns: prediction, the scikit-learn convention). Treat each class against the rest: , (its column off the diagonal), and (its row). This gives precision, recall and per class, with three ways to summarize them:
- Macro: simple average of the per-class metrics. Every class has equal weight, so a poorly classified rare class shows up. Macro recall is multiclass balanced accuracy.
- Weighted: average weighted by each class’s support . Frequent classes carry more weight.
- Micro: sum , and across classes, then calculate the metric once. Every example weighs the same.
In multiclass classification with one label per example, each error is both an FP (for the predicted class) and an FN (for the true class), so : micro precision, micro recall and micro coincide and equal accuracy exactly. Weighted recall adds nothing new either: . One detail: “macro ” has two definitions in use, the mean of per-class scores (scikit-learn’s) and the of macro precision and macro recall; these generally differ. Always say which you use.
import numpy as np
from sklearn.metrics import confusion_matrix, precision_recall_fscore_support, accuracy_score
def matriz_confusion(y, yhat, K):
C = np.zeros((K, K), dtype=int)
np.add.at(C, (y, yhat), 1) # fila = clase real, columna = predicha
return C
def por_clase(C):
vp = np.diag(C).astype(float)
predichos = C.sum(axis=0) # VP + FP de cada clase
soporte = C.sum(axis=1) # VP + FN de cada clase
prec = np.divide(vp, predichos, out=np.zeros_like(vp), where=predichos > 0)
sens = np.divide(vp, soporte, out=np.zeros_like(vp), where=soporte > 0)
f1 = np.divide(2 * prec * sens, prec + sens, out=np.zeros_like(vp), where=prec + sens > 0)
return prec, sens, f1, soporte
def promedios(C):
prec, sens, f1, soporte = por_clase(C)
w = soporte / soporte.sum()
vp = np.trace(C)
fp = C.sum() - vp # una etiqueta por ejemplo: suma de FP = suma de FN
micro = vp / (vp + fp)
return {"macro": (prec.mean(), sens.mean(), f1.mean()),
"ponderado": (w @ prec, w @ sens, w @ f1),
"micro": (micro, micro, micro)}
# un clasificador de tráfico con tres clases muy desequilibradas
clases = ["benigno", "sospechoso", "malicioso"]
C_obj = np.array([[850, 40, 10],
[ 20, 55, 5],
[ 5, 7, 8]])
y = np.repeat(np.repeat(np.arange(3), 3), C_obj.ravel()) # clase real de cada ejemplo
yhat = np.repeat(np.tile(np.arange(3), 3), C_obj.ravel()) # clase predicha
C = matriz_confusion(y, yhat, 3)
assert (C == confusion_matrix(y, yhat)).all()
prec, sens, f1, sop = por_clase(C)
for k in range(3):
print(f"{clases[k]:10s} soporte={sop[k]:4d} precisión={prec[k]:.3f} sensibilidad={sens[k]:.3f} F1={f1[k]:.3f}")
print(f"exactitud = {accuracy_score(y, yhat):.3f}")
for modo, (p, r, f) in promedios(C).items():
pk, rk, fk, _ = precision_recall_fscore_support(y, yhat, average={"ponderado": "weighted"}.get(modo, modo))
print(f"{modo:9s} P={p:.3f} R={r:.3f} F1={f:.3f} sklearn: P={pk:.3f} R={rk:.3f} F1={fk:.3f}")The malicious class, with 20 examples, has recall and precision (): the model misses 12 of 20 and is wrong two times out of three when it predicts that class. The weighted average () barely sees this because the class weighs 2%. Micro equals accuracy, , as shown above, as does weighted recall. Only macro (, recall ) reflects that two of the three classes perform poorly. If the rare class is what matters, weighted or micro averages hide exactly what you wanted to measure.
Rankings: the ROC curve
Moving the threshold traces a family of classifiers. The ROC (receiver operating characteristic, a name inherited from radar signal detection theory) plots them all at once.
Properties that follow from the definition:
- It runs from (threshold : nothing positive) to (threshold : everything positive) and increases monotonically in both coordinates.
- It does not depend on prevalence, because both rates are conditioned on class.
- It is invariant under strictly increasing score transformations: , and rank identically and have the same ROC. ROC sees order, not values. A model with implausible but perfectly ordered probabilities has a perfect ROC.
- The diagonal corresponds to a score independent of class: for every , AUC . A curve below the diagonal is a good curve with its sign reversed.
- Every point on the segment between two reachable points is reachable: randomly use one classifier or the other in the appropriate proportion. Thus the ROC’s convex hull is also reachable and underlies ROCCH classifier selection, summarized by Fawcett (2006). Tie segments are exactly of this kind: crossing a tie diagonally is equivalent to random tie-breaking.
- If and have densities and , the ROC slope at threshold is , the likelihood ratio. It will return when we discuss costs.
AUC is the probability of ordering a pair correctly
The area has an interpretation that makes it the quintessential ranking metric.
Proof
We prove the case where the distribution function of is continuous; you will handle the empirical case with ties in a guided exercise. As drops from to , increases continuously from 0 to 1 and the area is the Stieltjes integral
(Where is constant, the ROC has vertical segments with no area, ignored by the integral.) By independence and Fubini’s theorem, the last integral is . Since has no atoms, , and , the stated formula with a zero tie term.
∎The theorem says AUC is the probability that, given a random positive and negative, the model scores the positive higher, with ties worth half a win. The empirical estimator averages over pairs, the normalized statistic: AUC and the Mann-Whitney test use the same calculation. This gives AUC a complete error theory (it is a U-statistic, unbiased for the population probability, with calculable variance; DeLong, DeLong and Clarke-Pearson (1988) gave the standard method for comparing AUCs of models evaluated on the same cases, revisited when comparing models with paired tests).
Why the grid works: the first negative in the list (the highest-scoring one) is first to cross the falling threshold, and ROC steps right by . By then every higher-scoring positive has crossed too, so without ties the ROC height over that column is (number of positives beating it); a tie makes the step diagonal, leaving half a cell below the curve. Column area is times that count: pairs won by the positive. In the lesson’s example (6 positives and 8 negatives), 35 pairs are correctly ordered, 12 inverted and one tied at , so . ROC cells are the Mann-Whitney pairs.
The binormal model
An explicit model helps reasoning and is used by every interactive in the lesson: scores and , with the separation in standard deviations (the of signal detection theory). Since and , eliminating gives the entire curve:
and by the theorem, since ,
An AUC of corresponds to . With different variances, , the same calculation gives .
Computing ROC: sort once
Computing and separately at every threshold costs per threshold and overall. This is unnecessary: sorting scores descending means lowering the threshold to the next distinct score only adds examples with that score, so one pass accumulating and gives the entire curve in (sorting dominates). This is algorithm 1 of Fawcett (2006). The tricky detail is ties: emit a point only when the score changes, so all tied examples enter together and the curve moves diagonally. Processing them one by one makes the curve depend on the arbitrary order left by sorting: positives first yields an optimistic curve and negatives first a pessimistic one. You will see this in the lab and fix it in an exercise.
Multiclass AUC
With classes and a probability vector per example, there are two standard generalizations, both implemented by scikit-learn’s roc_auc_score:
- One versus rest (
multi_class="ovr"): for each class , binary AUC of score with class positive and the rest negative; then take a macro or prevalence-weighted average. Since the composition of “the rest” changes with prevalence, it depends on prevalence. - One versus one (
multi_class="ovo"): the measure of Hand and Till (2001). For each pair , is the probability that an example of class has higher than one of class , and is averaged over the pairs. It uses examples from only two classes at a time and does not depend on prevalence.
What AUC does not say
AUC averages over all thresholds, including those you would never use: with 1% positives and capacity to review 50 alerts a day, only the leftmost part of ROC matters, and two models with the same AUC can differ greatly there (their curves cross). Nor does it say anything about calibration, because it is invariant to increasing score transformations. As you will now see, it does not reflect how hard positives are to find when they are rare.
Precision-recall curves
The PR curve is not monotonic: as the threshold falls, recall never decreases, but precision rises or falls depending on whether a positive or negative enters, producing a sawtooth in small samples. Its baseline is not diagonal: a random-scoring classifier has precision at every threshold, so the reference is the horizontal line and average precision of random scores is (in the population; slightly more in a finite sample), not .
For a fixed evaluation set, ROC and PR contain the same information: each point with converts to a PR point with and the earlier Bayes formula for precision, and vice versa. Davis and Goadrich (2006) also showed that with fixed and , one curve dominates another in ROC space if and only if it dominates in PR space. But when curves cross, the summary changes: maximizing AUC does not maximize PR area, and the ordering of two models can reverse.
The practical difference is prevalence. ROC does not depend on ; PR does, strongly, through precision.
The next cell calculates the interactive’s numbers for the binormal model with AUC , at recall .
import numpy as np
from scipy.stats import norm
d = np.sqrt(2) * norm.ppf(0.95) # AUC = Phi(d / sqrt 2) = 0.95
t = np.linspace(-8, d + 8, 20001) # umbrales de mayor a menor recorrido
tpr, fpr = norm.sf(t - d), norm.sf(t)
auc = -np.sum(np.diff(fpr) * (tpr[1:] + tpr[:-1]) / 2)
t08 = d - norm.ppf(0.8) # umbral con sensibilidad 0.8
fpr08 = norm.sf(t08)
print(f"d' = {d:.3f} AUC = {auc:.4f} FPR en sensibilidad 0.8 = {fpr08:.4f}")
for pi in [0.5, 0.1, 0.01, 0.001]:
prec = pi * tpr / (pi * tpr + (1 - pi) * fpr)
pm = -np.sum(np.diff(tpr) * prec[1:]) # precisión media = integral de P dR
p08 = pi * 0.8 / (pi * 0.8 + (1 - pi) * fpr08)
print(f"pi = {pi:<6} precisión en R=0.8: {p08:.4f} FP por VP: {(1 - pi) * fpr08 / (pi * 0.8):6.2f} PM: {pm:.4f}")With , the point at recall has precision and average precision . With , the same classifier, with the same ROC and a false-positive rate of only , has precision : 8.5 false alarms per hit. With , precision is and average precision . This is the situation described by Saito and Rehmsmeier (2015): with imbalanced data a visual ROC reading can mislead about the reliability of positive predictions, due to an intuitive but incorrect interpretation of specificity: a “small” FPR is multiplied by a huge number of negatives. PR directly measures the fraction of correct positive predictions and therefore better anticipates performance in use. Their warning applies to many published studies evaluating ROC on highly imbalanced data.
This does not make ROC inferior. If deployment prevalence is unknown or will change, ROC (and AUC) describe separation ability without mixing in , while PR from an evaluation set with different prevalence would mislead in the opposite direction. A useful rule: use ROC to compare ranking ability; use PR at real prevalence to know the value of your alerts.
Why PR is not linearly interpolated
In ROC space the segment between two attainable points is attainable. In PR space it is not. Between consecutive thresholds and , randomization moves counts in a straight line: with additional positives, and , where is the number of negatives entering per positive. Precision along the segment is
a hyperbola in recall , not a line. With and , differentiation gives and : when precision decreases along the segment (, occurring when more negatives enter per positive than the cumulative ratio, , typical for a concave ROC), , the curve is convex and lies below the chord. Linear interpolation overestimates achievable precision, as Davis and Goadrich showed. The effect is negligible with one point per example and grows with few thresholds: a tree with few leaves, rounded scores, or many ties.
import numpy as np
from sklearn.metrics import precision_recall_curve, average_precision_score, auc, roc_curve
rng = np.random.default_rng(3)
n1, n0 = 200, 4000
s = np.r_[rng.normal(1.8, 1, n1), rng.normal(0, 1, n0)]
y = np.r_[np.ones(n1), np.zeros(n0)]
def area_pr_correcta(y, s, n1, n0):
"""Área bajo la PR alcanzable: interpola VP y FP en línea recta entre umbrales (Davis y Goadrich)."""
fpr, tpr, _ = roc_curve(y, s, drop_intermediate=False)
VP, FP = tpr * n1, fpr * n0
area = 0.0
for a in range(len(VP) - 1):
if VP[a + 1] == VP[a]:
continue # tramo sin positivos nuevos: no suma sensibilidad
k = (FP[a + 1] - FP[a]) / (VP[a + 1] - VP[a])
x = np.linspace(0, VP[a + 1] - VP[a], 401)
den = VP[a] + FP[a] + (1 + k) * x
P = (VP[a] + x) / np.where(den > 0, den, 1.0)
if VP[a] + FP[a] == 0:
P[0] = P[1] # en el origen la precisión es el límite 1/(1+k)
area += np.sum((P[1:] + P[:-1]) / 2 * np.diff(x)) / n1
return area
for nombre, sc in [("continua", s), ("5 niveles", np.clip(np.round(s), -1, 3))]:
prec, rec, _ = precision_recall_curve(y, sc)
print(f"{nombre:10s} umbrales={len(prec) - 1:5d} PM={average_precision_score(y, sc):.4f} "
f"trapecios={auc(rec, prec):.4f} correcta={area_pr_correcta(y, sc, n1, n0):.4f}")With continuous scores (4200 thresholds) the three figures agree nearly to the third decimal: , and . With the same scores rounded to 5 levels, trapezoids give when truly achievable area is : an overestimate of 8.6 points that can decide a model comparison. Stepwise average precision () is more conservative than the correct area, because each segment uses precision at its final endpoint, lowest when precision decreases. This is why scikit-learn computes AP without interpolation and warns that PR trapezoids can be overly optimistic.
Cost-sensitive decisions: the optimal threshold
Until now the threshold was a free parameter. If errors have costs, it ceases to be one. Let be the cost of a false positive (wasted review of a healthy function) and the cost of a false negative (a vulnerability reaching production), with correct decisions costing 0. If the model returns the true probability (a conditional probability), each decision has a conditional expected cost:
This is the cost-sensitive decision threshold, Elkan’s (2001) central result; he also notes that adding a constant to the costs for the same true class does not change the decision, so differences and suffice. The proof is short and you will reconstruct it in a guided exercise; the idea is that total cost is the average over of conditional cost, minimized by choosing the best decision for each separately. With , : reviewing any function with over 2% probability of vulnerability is worthwhile.
The assumption matters: must be the true probability. If a model ranks well but its numbers are not probabilities, the rule applies the right threshold on the wrong scale. Probabilities meaning what they say is called calibration, covered in later lessons.
import numpy as np
from scipy.stats import norm
from scipy.optimize import minimize_scalar
from scipy.special import expit, logit
d = np.sqrt(2) * norm.ppf(0.95)
pi, c_fp, c_fn = 0.02, 1.0, 10.0
p_star = c_fp / (c_fp + c_fn)
def coste(s):
"""Coste esperado por caso si se predice positivo cuando la puntuación binormal supera s."""
return c_fp * (1 - pi) * norm.sf(s) + c_fn * pi * norm.cdf(s - d)
# umbral de puntuación s que corresponde a un umbral t (en logit) sobre la probabilidad de cada modelo
modelos = {
"calibrado": lambda lt: (lt - logit(pi) + d * d / 2) / d, # logit q = d s - d²/2 + logit pi
"entrenado al 50 %": lambda lt: (lt + d * d / 2) / d, # logit q = d s - d²/2
"sobreconfiado": lambda lt: (lt / 2 - logit(pi) + d * d / 2) / d, # logit q = 2 logit p
}
print(f"p* = {p_star:.4f} siempre negativo: {c_fn * pi:.3f} siempre positivo: {c_fp * (1 - pi):.3f}")
for nombre, s_de in modelos.items():
r = minimize_scalar(lambda lt: coste(s_de(lt)), bounds=(-12, 12), method="bounded", options={"xatol": 1e-10})
c_p = coste(s_de(logit(p_star)))
print(f"{nombre:18s} umbral óptimo = {expit(r.x):.4f} coste mínimo = {r.fun:.5f} "
f"coste con p* = {c_p:.5f} (+{100 * (c_p / r.fun - 1):.0f} %)")With , and , the rule gives and is exact for the calibrated model. The model trained at 50% reaches the same minimum cost, per case, but at threshold : applying costs per case, 349% more, worse even than never flagging anything (). The overconfident model’s optimum is and it loses 17% using . The general lesson: miscalibration does not change how well a model can decide (the curve’s minimum), but where its good threshold lies. With calibrated probabilities the threshold follows from costs; otherwise search for it with data or recalibrate first.
The operating point in ROC space
The same calculation has a geometric interpretation. The expected cost per case at an ROC point is
so equal-cost points lie on lines with slope , and the best point is the last touched by such a line as it moves upward and left: on a smooth concave ROC, where the curve’s slope equals . That slope is the likelihood ratio , and by Bayes the posterior probabilities satisfy , that is, : both derivations give the same threshold. Geometry shows where the optimum falls: with high prevalence and similar costs, is small and the optimum lies at the top right; with rare positives, grows like (unless compensates) and the optimum moves to ROC’s far left, the region barely weighted by AUC. It has a practical advantage: it works even for an uncalibrated model because it uses only counts.
Other operating-point criteria apply when costs cannot be quantified: minimum recall (“find 95% of vulnerabilities”), an alert budget (“review the 50 highest-scoring functions per day,” setting a quantile threshold), or the Neyman-Pearson formulation (maximum recall with ). Choose all of these using validation data, never test data: optimizing a threshold on the test set makes it another training set and its figure no longer estimates production behavior (the same principle as holdout validation).
Class imbalance
One percent positives is not itself a disease of the model. If the classifier is trained with a loss estimating probabilities (log-loss is a proper scoring rule) and there is enough data, it also learns for the rare class, and the cost rule handles decisions. Real problems are different: metrics hiding the rare class (accuracy), the default threshold (optimal only if ), variance from few positives, and some algorithms dedicating little capacity to them. Elkan (2001) summarizes that for standard Bayesian and decision-tree methods, changing training class proportions has little effect on the resulting classifier, and recommends training on data as received and deciding afterward using probabilities and costs.
Nevertheless rebalancing techniques are used daily, and we need to know exactly what they do to probabilities.
The first three change the effective prevalence seen in training, and thus the probabilities the model learns. The calculation is exact in the population. For weights: the minimizer of weighted log-loss at a point maximizes over ; differentiation gives , so
Weights multiply odds by . Undersampling negatives at fraction is the same with , (in expectation, with less data), and replicating positives times is the same with . With class_weight="balanced" in a binary problem, : the model learns odds for a population at 50% prevalence. An often overlooked consequence: applying threshold to that model is equivalent to predicting positive when , which the cost theorem says is optimal only if . With , rebalancing and using declares a false negative costs 99 false positives, whether you realize it or not.
The inverse operation is the correction of Saerens, Latinne and Decaestecker (2002).
Proof
By Bayes, , hence . Substituting in , the factor cancels, giving the formula. In the binary case, the ratio between and gives odds: , and taking logs gives the second form.
∎The assumption, called label shift, is exactly what holds when you cause the prevalence change by classwise resampling. Saerens et al. also propose an EM algorithm to estimate unknown new priors from predictions on unlabeled deployment data. Elkan (2001) uses the same calculation in reverse: if you want a resampled model’s usual threshold to correspond to the cost threshold , multiply the number of negatives by .
Lab: imbalance and thresholds
A synthetic problem with 1% positives: six Gaussian features of variance 1, shifted for positives by . Since both classes are Gaussian with the same covariance, logistic regression is well specified (its true logit is linear), so differences among methods come from imbalance handling rather than an unsuitable model. Training, validation and test are independent samples; costs are and , so .
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score, average_precision_score
rng = np.random.default_rng(0)
mu = np.array([1.0, 0.8, 0.6, 0.4, 0.2, 0.0])
def muestra(n, pi=0.01):
y = (rng.random(n) < pi).astype(int)
X = rng.normal(size=(n, len(mu))) + np.outer(y, mu)
return X, y
Xtr, ytr = muestra(30_000)
Xva, yva = muestra(30_000)
Xte, yte = muestra(100_000)
print("positivos en entrenamiento, validación y test:", ytr.sum(), yva.sum(), yte.sum())
c_fp, c_fn = 1.0, 50.0
p_star = c_fp / (c_fp + c_fn)
def coste(y, yhat):
return (c_fp * np.sum((yhat == 1) & (y == 0)) + c_fn * np.sum((yhat == 0) & (y == 1))) / len(y)
def corregir(p, pi_entreno, pi_real):
"""Corrección de priors binaria: desplaza el logit."""
z = np.log(p / (1 - p)) + np.log(pi_real / (1 - pi_real)) - np.log(pi_entreno / (1 - pi_entreno))
return 1 / (1 + np.exp(-z))
def smote(Xpos, n_nuevos, k=5):
d2 = ((Xpos[:, None, :] - Xpos[None, :, :]) ** 2).sum(-1)
np.fill_diagonal(d2, np.inf)
vecinos = np.argsort(d2, axis=1)[:, :k]
i = rng.integers(len(Xpos), size=n_nuevos)
j = vecinos[i, rng.integers(k, size=n_nuevos)]
u = rng.random((n_nuevos, 1))
return Xpos[i] + u * (Xpos[j] - Xpos[i])
LR = lambda **kw: LogisticRegression(C=1e4, max_iter=1000, **kw) # casi sin regularización
pi_tr = ytr.mean()
modelos = {}
modelos["tal cual"] = LR().fit(Xtr, ytr)
modelos["class_weight"] = LR(class_weight="balanced").fit(Xtr, ytr)
pos, neg = np.flatnonzero(ytr == 1), np.flatnonzero(ytr == 0)
sub = np.r_[pos, rng.choice(neg, size=len(pos), replace=False)] # submuestreo hasta el 50 %
modelos["submuestreo"] = LR().fit(Xtr[sub], ytr[sub])
n_sint = len(neg) - len(pos)
Xs = np.r_[Xtr, smote(Xtr[pos], n_sint)]
ys = np.r_[ytr, np.ones(n_sint, dtype=int)]
modelos["SMOTE"] = LR().fit(Xs, ys)
p_te = {k: m.predict_proba(Xte)[:, 1] for k, m in modelos.items()}filas = [("tal cual", "umbral 0.5", p_te["tal cual"], 0.5),
("tal cual", "umbral p*", p_te["tal cual"], p_star)]
for k in ["class_weight", "submuestreo", "SMOTE"]:
filas.append((k, "umbral 0.5", p_te[k], 0.5))
filas.append((k, "umbral p*", p_te[k], p_star))
filas.append((k, "corregido + p*", corregir(p_te[k], 0.5, pi_tr), p_star))
# referencia: el clasificador de Bayes con el logit verdadero
logit_real = Xte @ mu - mu @ mu / 2 + np.log(0.01 / 0.99)
p_bayes = 1 / (1 + np.exp(-logit_real))
print(f"{'modelo':13s} {'decisión':15s} AUC PM media p sens. prec. coste")
for nombre, regla, p, t in filas + [("Bayes", "umbral p*", p_bayes, p_star)]:
yhat = (p >= t).astype(int)
sens = yhat[yte == 1].mean()
prec = yte[yhat == 1].mean() if yhat.any() else float("nan")
print(f"{nombre:13s} {regla:15s} {roc_auc_score(yte, p):.4f} {average_precision_score(yte, p):.4f} "
f"{p.mean():.4f} {sens:.3f} {prec:.3f} {coste(yte, yhat):.4f}")
print(f"no marcar nada: coste {c_fn * yte.mean():.4f}")Read the table by columns.
- AUC and average precision are nearly equal across all four models and close to the Bayes classifier’s. Weights, undersampling and SMOTE did not improve ranking: with a well-specified model they only change the probability scale (corrections are increasing, so they preserve order and leave AUC and AP unchanged).
- Mean probability reveals the scale. The untreated model predicts on average, the real prevalence; the three rebalanced models average between and , over 30 times more: they think they live in a 50% population.
- Cost separates decisions. Threshold on the untreated model flags almost nothing (recall ) and costs per case, almost the same as never flagging (). The same model with costs , close to the Bayes classifier’s . For rebalanced models, works badly: they flag almost everything (recall , precision ) and cost between and , because inflated probabilities are compared with a threshold intended for real probabilities. At they land between these ( to ), optimal for , not 50. After prior correction, all three return to a mean near and with cost between and , 0.6% to 1.2% above the untreated model.
What about choosing the threshold directly on validation data, minimizing empirical cost? This is the alternative when calibration is untrustworthy. Its price is variance: with 280 validation positives, empirical cost is a noisy step function of the threshold.
p_va = modelos["tal cual"].predict_proba(Xva)[:, 1]
def umbral_validacion(p, y):
"""Umbral con el menor coste empírico: ordenar una vez y probar todos los cortes en O(n log n)."""
orden = np.argsort(-p)
vp = np.cumsum(y[orden]) # VP si se marcan los k primeros
fp = np.arange(1, len(p) + 1) - vp
c = c_fp * fp + c_fn * (y.sum() - vp)
return p[orden][np.argmin(c)]
t_val = umbral_validacion(p_va, yva)
yhat = lambda t: (p_te["tal cual"] >= t).astype(int)
print(f"esta validación: umbral {t_val:.4f}, coste en test {coste(yte, yhat(t_val)):.4f} p* = {p_star:.4f}: {coste(yte, yhat(p_star)):.4f}")
costes = []
for r in range(20): # otras 20 validaciones independientes del mismo tamaño
Xv, yv = muestra(30_000)
tv = umbral_validacion(modelos["tal cual"].predict_proba(Xv)[:, 1], yv)
costes.append(coste(yte, yhat(tv)))
costes = np.array(costes)
print(f"umbral de validación en 20 repeticiones: coste en test medio {costes.mean():.4f}, "
f"rango [{costes.min():.4f}, {costes.max():.4f}]; peor que p* en {np.sum(costes > coste(yte, yhat(p_star)))} de 20")This validation’s threshold () costs on test versus for . It is not bad luck: across 20 independent validations of the same size, empirical threshold cost averages , loses to in 15 of 20, and reaches in the worst. With a well-calibrated model, has no selection variance and generally beats the validation-selected threshold; empirical selection pays off when calibration is doubtful, and then smoothing it (cross-validation, more validation data) or, better, recalibrating is advisable.
The last experiment illustrates a common error: resampling before splitting.
from sklearn.tree import DecisionTreeClassifier
X, y = muestra(20_000)
rep = np.r_[np.arange(len(y)), np.repeat(np.flatnonzero(y == 1), 20)] # cada positivo, 21 veces
perm = rng.permutation(len(rep))
a, b = rep[perm[: len(rep) // 2]], rep[perm[len(rep) // 2:]] # dividir DESPUÉS de replicar
arbol = DecisionTreeClassifier(random_state=0).fit(X[a], y[a])
pv = arbol.predict_proba(X[b])[:, 1]
print(f"mal (replicar y luego dividir): AUC de validación = {roc_auc_score(y[b], pv):.3f}, PM = {average_precision_score(y[b], pv):.3f}")
print(f" el mismo árbol en test limpio: AUC = {roc_auc_score(yte, arbol.predict_proba(Xte)[:, 1]):.3f}")
perm = rng.permutation(len(y))
a, b = perm[:10_000], perm[10_000:] # dividir ANTES de replicar
a_rep = np.r_[a, np.repeat(a[y[a] == 1], 20)]
arbol = DecisionTreeClassifier(random_state=0).fit(X[a_rep], y[a_rep])
pv = arbol.predict_proba(X[b])[:, 1]
print(f"bien (dividir y luego replicar): AUC de validación = {roc_auc_score(y[b], pv):.3f}, PM = {average_precision_score(y[b], pv):.3f}")Replicating before splitting leaves exact copies of almost all validation positives in training, and an unpruned tree memorizes them: validation promises an AUC near 1 when the same tree barely beats chance on clean data. Split first and validation tells the truth. SMOTE has the same issue because synthetic points interpolate positives that would end up on both sides of the split. This is a case of data leakage, covered in depth next lesson along with cross-validation, where resampling must happen inside each fold.
Regression metrics
Regression has no threshold; the question is which point prediction each metric rewards. The module’s first lesson answered for losses: squared error is minimized by the conditional mean and absolute error by the median. Evaluation metrics inherit that property, and those that are not a familiar loss hide their own functional.
What each rewards:
- RMSE: the square root of mean squared error is an increasing transformation, so it shares the minimizer: the conditional mean. It is in units of and heavily weights large errors; one outlier can dominate it.
- MAE: the conditional median. More robust, but indifferent to small versus large errors in the tail.
- : on a fixed set it is , a decreasing transformation of MSE with the same minimizer. Its normalization depends on evaluation-set variance: the same model has a higher on a more dispersed test set, so do not compare it across sets. Outside training it may be negative (simply predict worse than the test mean) and does not equal squared correlation between and . A constant has .
- MAPE: a scale-independent relative error that is easy to communicate, but infinite if any and explosive near zero. Its minimizer is not the median: Gneiting (2011) showed that for , MAPE is consistent with the median of the distribution with density proportional to , never above the median (weight shifts mass toward small values). MAPE rewards underprediction. See it without calculation: for fixed and nonnegative predictions, an underestimate costs at most 100%, while overestimates have no ceiling.
- sMAPE: designed to correct that asymmetry, it partly reverses it. With , predicting costs and predicting costs : same absolute error, different penalty, now against underprediction. Hyndman and Koehler (2006) review these pathologies and propose scaling errors by a naive predictor’s errors (MASE) when comparing series with different scales.
The interactive’s model has exact minimizers. For , normalized density is another lognormal, (multiplying by shifts the logarithm’s mean by ), whose median is . The cell checks this by numerically minimizing each metric on a sample, including sMAPE, which has no closed form.
import numpy as np
from scipy.optimize import minimize_scalar
rng = np.random.default_rng(7)
s = 0.75
y = rng.lognormal(0.0, s, 50_000)
metricas = {
"RMSE": lambda c: np.sqrt(np.mean((y - c) ** 2)),
"MAE": lambda c: np.mean(np.abs(y - c)),
"MAPE": lambda c: 100 * np.mean(np.abs(y - c) / y),
"sMAPE": lambda c: 100 * np.mean(2 * np.abs(y - c) / (y + c)),
}
teoria = {"RMSE": np.exp(s**2 / 2), "MAE": 1.0, "MAPE": np.exp(-s**2), "sMAPE": float("nan")}
for nombre, f in metricas.items():
r = minimize_scalar(f, bounds=(0.05, 5), method="bounded")
print(f"{nombre:6s} mejor constante = {r.x:.3f} teoría = {teoria[nombre]:.3f} valor = {r.fun:.3f}")
# el R^2 de las constantes y el MAPE cerca de cero
var = np.mean((y - y.mean()) ** 2)
for c in [y.mean(), 1.0, np.exp(-s**2)]:
print(f"R² de la constante {c:.3f}: {1 - np.mean((y - c) ** 2) / var:+.3f}")
y_cero = np.r_[y[:999], 1e-6] # un solo valor real casi nulo entre 1000
print(f"MAPE de la mediana con 1000 valores: {100 * np.mean(np.abs(y[:1000] - 1) / y[:1000]):.1f} %;"
f" cambiando uno por 1e-6: {100 * np.mean(np.abs(y_cero - 1) / y_cero):.1f} %")The sample confirms theory: optimal constants are , and , versus population mean (RMSE), median (MAE) and (MAPE); differences are sampling noise. For this distribution sMAPE chooses almost the median (), but not by a general principle: it corresponds to no simple functional. These are “best predictions” of the same distribution under reasonable metrics, and MAPE’s is 57% lower than RMSE’s. If evaluated on MAPE, a model trained with squared error will systematically predict above what the metric rewards: evaluation metric and training loss should estimate the same functional. Sample-mean is exactly 0, and that of any other constant is negative. The final two lines show the zero pathology: one true value of among a thousand takes the median’s MAPE from to over .
Implementation from scratch and sklearn.metrics equivalents
You already have the multiclass confusion matrix. Remaining are ROC, AUC in two ways, and average precision. Start with a naive ROC that processes examples one at a time to see what it does with ties.
import numpy as np
from sklearn.metrics import roc_auc_score, average_precision_score
def roc_ingenua(y, s, positivos_primero=False):
"""Un punto por EJEMPLO tras ordenar; los empates quedan en el orden en que los deje la ordenación."""
y = np.asarray(y)
clave = (-np.asarray(s, float), -y if positivos_primero else y)
orden = np.lexsort(clave[::-1]) # ordena por -s y, a igualdad, por la clase
ys = y[orden]
vp = np.r_[0, np.cumsum(ys)]
fp = np.r_[0, np.cumsum(1 - ys)]
return fp / fp[-1], vp / vp[-1]
def area_trapecios(x, h):
return float(np.sum(np.diff(x) * (h[1:] + h[:-1]) / 2))
def rangos_medios(s):
"""Rangos 1..n con los empates promediados, en O(n log n)."""
s = np.asarray(s, float)
orden = np.argsort(s, kind="mergesort")
ss = s[orden]
ini = np.r_[0, np.flatnonzero(np.diff(ss)) + 1]
fin = np.r_[ini[1:], len(s)]
r = np.empty(len(s))
r[orden] = np.repeat((ini + fin + 1) / 2, fin - ini)
return r
def auc_mann_whitney(y, s):
y = np.asarray(y)
n1 = y.sum(); n0 = len(y) - n1
U = rangos_medios(s)[y == 1].sum() - n1 * (n1 + 1) / 2
return U / (n1 * n0)
def precision_media(y, s):
"""PM = suma de (R_k - R_{k-1}) P_k, con un punto por puntuación distinta."""
y = np.asarray(y); s = np.asarray(s, float)
_, grupo = np.unique(-s, return_inverse=True) # grupo 0 = la puntuación más alta
vp = np.cumsum(np.bincount(grupo.ravel(), weights=y)) # VP acumulados por umbral
marcados = np.cumsum(np.bincount(grupo.ravel())) # VP + FP acumulados
R = np.r_[0, vp / y.sum()]
return float(np.sum(np.diff(R) * vp / marcados))
rng = np.random.default_rng(1)
n = 200_000
y = (rng.random(n) < 0.05).astype(int)
s = np.round(rng.normal(size=n) + 1.5 * y, 1) # redondeo a 0.1: muchísimos empates
for primero in [True, False]:
f, t = roc_ingenua(y, s, positivos_primero=primero)
print(f"ROC ingenua, empates con los {'positivos' if primero else 'negativos'} delante: AUC = {area_trapecios(f, t):.4f}")
print(f"Mann-Whitney con rangos medios: AUC = {auc_mann_whitney(y, s):.4f} sklearn: {roc_auc_score(y, s):.4f}")
print(f"precisión media desde cero: PM = {precision_media(y, s):.4f} sklearn: {average_precision_score(y, s):.4f}")
s_cont = s + rng.normal(scale=1e-9, size=n) # sin empates, la versión ingenua ya es correcta
f, t = roc_ingenua(y, s_cont)
print(f"sin empates: ingenua {area_trapecios(f, t):.4f} Mann-Whitney {auc_mann_whitney(y, s_cont):.4f} sklearn {roc_auc_score(y, s_cont):.4f}")With 200,000 examples and scores rounded to one decimal, naive ROC gives two different AUCs depending on tie order, with positives first and with negatives first, while the correct value (Mann-Whitney with average ranks, counting each tie as half a pair), , matches scikit-learn and lies exactly between them: the optimistic version counts every tied pair as a win, the pessimistic one as a loss. Without ties all three agree. Writing the correct ROC, which groups ties in one step, is an exercise at the end. The table summarizes equivalent scikit-learn functions:
| From scratch | sklearn.metrics | Notes |
|---|---|---|
matriz_confusion | confusion_matrix(y, yhat) | rows: true class; columns: predicted class |
por_clase, promedios | precision_recall_fscore_support(..., average=None / "macro" / "micro" / "weighted"), classification_report | zero_division decides what to do with 0/0 |
fbeta_score(y, yhat, beta=2) | ||
| balanced accuracy | balanced_accuracy_score | macro recall |
| ROC by sweep | roc_curve(y, s) | default drop_intermediate=True removes collinear points |
auc_mann_whitney | roc_auc_score(y, s); multiclass with multi_class="ovr" or "ovo" | "ovo" is the Hand and Till measure |
precision_media | average_precision_score(y, s), precision_recall_curve | steps, no interpolation |
| trapezoidal area | auc(x, y) | general: on PR it overestimates with few thresholds |
| RMSE, MAE, , MAPE | mean_squared_error (and its square root), mean_absolute_error, r2_score, mean_absolute_percentage_error | sklearn MAPE is a fraction, not a percentage |
Common mistakes
Exercises
More than one answer may be correct.
Step 1 of 4. What area lies under that segment?
Step 1 of 5. How do you decompose the expected cost of a rule ?
class_weight='balanced' and flag positive when its probability exceeds . Assuming the model exactly learns rescaled odds, for what cost ratio is that decision optimal?roc_curve_and_auc(y, scores), returning (fpr, tpr, auc): empirical ROC arrays, beginning at (0, 0) and then one point per distinct score in descending order (tied examples enter together), and trapezoidal area. It must match sklearn.metrics.roc_curve(y, scores, drop_intermediate=False) and roc_auc_score, and run in : no Python loops over examples or comparisons of all pairs.import numpy as np
def roc_curve_and_auc(y, scores):
"""Devuelve (fpr, tpr, auc) con un punto por puntuación distinta y los empates juntos."""
y = np.asarray(y)
scores = np.asarray(scores, dtype=float)
# tu código: ordenar de mayor a menor, localizar dónde cambia la puntuación,
# acumular VP y FP en esos puntos y añadir el (0, 0) inicial
fpr = np.array([0.0, 1.0])
tpr = np.array([0.0, 1.0])
auc = 0.0
return fpr, tpr, auccorregir_priors(P, pi_entreno, pi_real): P is an matrix of posterior probabilities from a model trained with priors pi_entreno (a vector of length ), and the function returns the matrix of probabilities corrected to priors pi_real, assuming only priors change (label shift). Each row must sum to 1.import numpy as np
def corregir_priors(P, pi_entreno, pi_real):
"""Corrige las probabilidades a posteriori de los priors de entrenamiento a los reales."""
P = np.asarray(P, dtype=float)
# tu código
return PSummary
- The confusion matrix summarizes one threshold. Recall, specificity and FPR are class-conditional and prevalence-independent; precision, accuracy and are not. In multiclass, micro and weighted averages count examples (micro equals accuracy) and macro counts classes.
- ROC sweeps all thresholds, does not depend on and sees only ranking. Its area is the probability of correctly ordering a positive-negative pair, with ties worth half: the normalized Mann-Whitney statistic. Compute it in by grouping ties.
- PR, with baseline , shows what ROC hides when positives are rare: an AUC of 0.95 can coexist with precision 0.1 if . Stepwise average precision summarizes it; straight-line interpolation overestimates area.
- With calibrated probabilities, the expected-cost-minimizing threshold is . A miscalibrated model reaches the same minimum cost at another threshold; choose the operating point on validation, never test.
- Weights, undersampling, oversampling and SMOTE multiply odds; they do not improve a well-specified model’s ranking, and probabilities should be corrected using Saerens’ formula before use. Always resample after splitting.
- In regression RMSE rewards the mean, MAE the median and MAPE a value below the median; depends on evaluation-set variance and MAPE explodes near zero. Metric and training loss should estimate the same thing.