Overview
A metric turns a pile of predictions into one number you can compare. No single number tells the whole story. Accuracy counts how often the model is right, which sounds complete until one class is rare: a model that always says no is 99 percent accurate when only 1 percent of cases are yes. Other metrics ask sharper questions. Of the cases flagged, how many were real? Of the real cases, how many were found? Does the model rank real cases above the rest? How wrong are its stated probabilities?
A short history
These metrics come from several fields. The receiver operating characteristic curve was developed for radar signal detection in the 1940s and moved into medicine and then machine learning. Precision and recall come from information retrieval research of the 1950s and 1960s, and C. J. van Rijsbergen's 1979 book gave the F measure that combines them. Mean squared error goes back to the least squares work of Gauss and Legendre in the early 1800s. Log loss comes from information theory and maximum likelihood.
How it works
- Choose the task in the config: binary (labels 0 and 1), multiclass (labels 0 to ) or regression.
- Call
Metrics.computewith the true labels and predicted labels, predicted scores, or both. Without labels, binary scores at or abovethresholdbecome class 1. - For classification, count each pair of true class and predicted class into the confusion matrix.
- Read precision, recall and F1 off the matrix, per class or averaged (macro, weighted or micro).
- From the scores, compute ROC AUC by ranking, and log loss from the probability given to the true class.
- For regression, compute MSE, RMSE, MAE and from the differences between targets and predictions.
Watch out for
- Accuracy on imbalanced classes rewards a model that ignores the rare class, because it is right about the common class almost every time.
- Precision, recall and F1 depend on the threshold, so two models compared at 0.5 may rank the other way round at another cut.
- ROC AUC only looks at the ordering of the scores, so a model can have a high AUC and still give probabilities that are far too high or too low.
- Log loss punishes a confident wrong answer very hard, so a single prediction near 0 for the true class can dominate the average.
- can be negative on held-out data, which means the model is worse than always predicting the mean.
Use cases
When to use it
After every training run and validation fold, and whenever a number from a framework needs an independent check. With a rare positive class read precision, recall and ROC AUC, not accuracy.
In industry
- Medical screening
- A screening test is judged by recall, the share of sick patients it finds, and by precision, the share of its alarms that are real, because accuracy hides a rare disease.
- Fraud detection
- Card fraud is a tiny share of transactions. Teams read precision, recall and ROC AUC, since a model that flags nothing is almost always accurate.
- Demand and price forecasting
- Regression models are compared on mean absolute error, which reads in the units of the target, and on mean squared error when large misses cost more.
Choosing it: what must hold
- True labels for the rows being scored, held out from training.
- A metric that matches the cost of each kind of error in the real decision.
- For ROC AUC and log loss, predicted scores or probabilities and not only hard labels.
- Enough positive examples that precision and recall are not decided by a handful of rows.
When to choose something else
| If | Use instead |
|---|---|
| You need to know how stable the number is across different splits | The holdout and cross-validation evaluation lesson |
| The output is a ranked list, as in search or recommendation | Ranking metrics such as NDCG or recall at k |
| The model is unsupervised and there are no labels | Measures such as reconstruction error for an Autoencoder or topic coherence for LDA |
Math foundations
Accuracy
The share of predictions that are correct. The four counts are the cells of the binary confusion matrix: true and false positives, true and false negatives.
Precision and recall
Precision asks how many of the flagged cases were real. Recall asks how many of the real cases were flagged. Raising the threshold usually trades recall for precision.
F1 score
The harmonic mean of the two. It is high only when both are high, so a model cannot hide a poor recall behind a perfect precision.
ROC AUC by ranks
Rank all scores from lowest (rank 1) upward, tied scores sharing their mean rank, and add up the ranks of the positives. The result is the chance that a random positive is scored above a random negative, ties counting one half.
Log loss
The average negative log of the probability the model gave to the true class. It is 0 for perfect confidence in the right answers and grows without limit as that probability nears 0, so the template clips probabilities by
eps.Squared and absolute error
Regression errors. Squaring makes large misses count much more than small ones. RMSE and MAE are in the units of the target.
Coefficient of determination
The share of the target's variation that the model explains. It is 1 for a perfect fit and 0 for a model no better than predicting the mean.
Symbols
- true positives and true negatives
- false positives and false negatives
- number of positive and negative samples
- sum of the ranks of the positive samples
- probability the model gave to the true class of sample i
- target and prediction for sample i
- mean of the targets
- number of samples
Worked by hand
True labels are 0, 0, 1, 1 and the scores are 0.1, 0.4, 0.35, 0.8. At the threshold 0.5 the predictions are 0, 0, 0, 1, so , , , . The score ranks are 1, 3, 2, 4.
Everything flagged was real (precision 1) but half the real cases were missed (recall 0.5). The AUC of 0.75 says three of the four positive and negative pairs are ordered correctly.
Visual example
Loading the example.
Try this
- Slide the threshold from 0.5 down to 0.2: recall rises, precision falls, and the AUC does not move.
- Click a cell of the confusion matrix to find its samples on the score line.
- Lower the separation to 0 and read what an AUC near 0.5 looks like.
Code sample
import numpy as np
from impl import Metrics
from config import MetricsConfig
y_true = np.array([0, 0, 1, 1])
y_score = np.array([0.1, 0.4, 0.35, 0.8])
result = Metrics(MetricsConfig(task="binary")).compute(y_true, y_score=y_score)
print(result["accuracy"], result["roc_auc"], result["confusion_matrix"]) # 0.75 0.75 [[2, 0], [1, 1]]
reg = Metrics(MetricsConfig(task="regression")).compute([3.0, 5.0, 7.0], [2.0, 5.0, 8.0])
print(reg["rmse"], reg["r2"]) # 0.816..., 0.75Read the implementation (162 lines)
"""Evaluation metrics for classification and regression, computed from first principles with NumPy.
Classification: confusion matrix, accuracy, precision, recall, F1 (binary or averaged over classes),
ROC AUC and log loss. Regression: MSE, RMSE, MAE and R^2. `Metrics.compute` picks the set for the task
and returns one dict.
"""
from __future__ import annotations
import numpy as np
try:
from .config import MetricsConfig
except ImportError: # run from the template's own folder
from config import MetricsConfig
def confusion_matrix(y_true, y_pred, n_classes: int | None = None) -> np.ndarray:
"""Counts of (true class, predicted class).
y_true, y_pred: integer labels 0..k-1, shape (n,).
Returns an int array of shape (k, k) where entry [i, j] is the number of samples of true class i
predicted as class j.
"""
y_true = np.asarray(y_true, dtype=int).reshape(-1)
y_pred = np.asarray(y_pred, dtype=int).reshape(-1)
if y_true.shape != y_pred.shape:
raise ValueError(f"y_true has {y_true.shape[0]} labels, y_pred has {y_pred.shape[0]}")
k = n_classes or int(max(y_true.max(), y_pred.max())) + 1
matrix = np.zeros((k, k), dtype=int)
np.add.at(matrix, (y_true, y_pred), 1)
return matrix
def _ratio(numerator, denominator):
"""numerator / denominator, with 0 where the denominator is 0 (a class nobody predicted or held)."""
numerator = np.asarray(numerator, dtype=float)
denominator = np.asarray(denominator, dtype=float)
return np.divide(numerator, denominator, out=np.zeros_like(numerator), where=denominator != 0)
def precision_recall_f1(matrix: np.ndarray, average: str | None = "macro") -> tuple:
"""Precision, recall and F1 from a confusion matrix of shape (k, k).
average: None returns three arrays of shape (k,), one value per class.
"macro" is the plain mean over classes, "weighted" weights each class by its number of true
samples, "micro" pools the counts of all classes first (and then equals accuracy).
"""
matrix = np.asarray(matrix, dtype=float)
true_pos = np.diag(matrix)
predicted = matrix.sum(axis=0) # column sums: how often each class was predicted
actual = matrix.sum(axis=1) # row sums: how often each class really occurs
if average == "micro":
p = r = float(_ratio(true_pos.sum(), matrix.sum()))
return p, r, float(_ratio(2 * p * r, p + r))
precision = _ratio(true_pos, predicted)
recall = _ratio(true_pos, actual)
f1 = _ratio(2 * precision * recall, precision + recall)
if average is None:
return precision, recall, f1
if average == "macro":
weights = np.full(len(actual), 1.0 / len(actual))
elif average == "weighted":
weights = actual / actual.sum()
else:
raise ValueError(f"unknown average {average!r}")
return float(precision @ weights), float(recall @ weights), float(f1 @ weights)
def roc_auc(y_true, y_score) -> float:
"""Area under the ROC curve for labels in {0, 1} and real-valued scores, shape (n,).
Computed as the probability that a random positive is scored above a random negative, with ties
counting one half (the Mann-Whitney U statistic divided by n_pos * n_neg).
"""
y_true = np.asarray(y_true, dtype=int).reshape(-1)
y_score = np.asarray(y_score, dtype=float).reshape(-1)
n_pos = int((y_true == 1).sum())
n_neg = int((y_true == 0).sum())
if n_pos == 0 or n_neg == 0:
raise ValueError("ROC AUC needs at least one positive and one negative sample")
_, inverse, counts = np.unique(y_score, return_inverse=True, return_counts=True)
last_rank = np.cumsum(counts) # 1-based rank of the last member of each tie group
average_rank = last_rank - (counts - 1) / 2.0 # tied scores share the mean of their ranks
ranks = average_rank[inverse]
return float((ranks[y_true == 1].sum() - n_pos * (n_pos + 1) / 2.0) / (n_pos * n_neg))
def log_loss(y_true, proba, eps: float = 1e-15) -> float:
"""Mean negative log-likelihood of the true class.
y_true: labels, shape (n,). proba: shape (n,) with P(class 1) for a binary task, or shape (n, k)
with one probability per class.
"""
y_true = np.asarray(y_true, dtype=int).reshape(-1)
proba = np.asarray(proba, dtype=float)
if proba.ndim == 1:
proba = np.stack([1.0 - proba, proba], axis=1)
picked = np.clip(proba[np.arange(len(y_true)), y_true], eps, 1.0 - eps)
return float(-np.log(picked).mean())
def regression_metrics(y_true, y_pred) -> dict:
"""MSE, RMSE, MAE and R^2 for targets and predictions of the same shape."""
y_true = np.asarray(y_true, dtype=float).reshape(-1)
y_pred = np.asarray(y_pred, dtype=float).reshape(-1)
if y_true.shape != y_pred.shape:
raise ValueError(f"y_true has {y_true.shape[0]} values, y_pred has {y_pred.shape[0]}")
residual = y_true - y_pred
mse = float((residual**2).mean())
total = float(((y_true - y_true.mean()) ** 2).sum())
# R^2 = 1 - SS_res / SS_tot. A constant target has SS_tot = 0: perfect predictions score 1, others 0.
r2 = 1.0 - float((residual**2).sum()) / total if total > 0 else float(mse == 0.0)
return {"mse": mse, "rmse": mse**0.5, "mae": float(np.abs(residual).mean()), "r2": r2}
class Metrics:
"""Compute the standard metric set for a task."""
def __init__(self, config: MetricsConfig | None = None) -> None:
self.config = config or MetricsConfig()
def compute(self, y_true, y_pred=None, y_score=None) -> dict:
"""Return a dict of metric name to value.
regression: y_pred are the predicted values, shape (n,).
binary: give y_score (P(class 1), shape (n,)), y_pred (0/1 labels), or both. Without y_pred the
labels come from y_score >= threshold. roc_auc and log_loss need y_score.
multiclass: give y_score (probabilities, shape (n, k)), y_pred (labels), or both. Without y_pred the
labels are the argmax of y_score. log_loss needs y_score.
"""
cfg = self.config
if cfg.task == "regression":
if y_pred is None:
raise ValueError("regression needs y_pred")
return regression_metrics(y_true, y_pred)
if y_pred is None and y_score is None:
raise ValueError("give y_pred, y_score or both")
y_true = np.asarray(y_true, dtype=int).reshape(-1)
score = None if y_score is None else np.asarray(y_score, dtype=float)
if cfg.task == "binary":
labels = (score >= cfg.threshold).astype(int) if y_pred is None else np.asarray(y_pred, dtype=int)
matrix = confusion_matrix(y_true, labels, n_classes=2)
precision, recall, f1 = (float(v[1]) for v in precision_recall_f1(matrix, average=None))
else:
labels = score.argmax(axis=1) if y_pred is None else np.asarray(y_pred, dtype=int)
k = score.shape[1] if score is not None else None
matrix = confusion_matrix(y_true, labels, n_classes=k)
precision, recall, f1 = precision_recall_f1(matrix, average=cfg.average)
out = {
"accuracy": float(np.trace(matrix) / matrix.sum()),
"precision": precision,
"recall": recall,
"f1": f1,
"confusion_matrix": matrix.tolist(),
}
if score is not None:
out["log_loss"] = log_loss(y_true, score, cfg.eps)
if cfg.task == "binary":
out["roc_auc"] = roc_auc(y_true, score)
return out- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 8, run with
python3 -m unittest -v
Practice
Run Metrics(MetricsConfig(task="binary")).compute(y_true, y_score=y_score) on the worked example and confirm the numbers. Then set threshold to 0.3 and to 0.7, and record how precision, recall and the confusion matrix move while roc_auc stays the same.
Check on learning
- A fraud model reaches 99.5 percent accuracy on data where 0.5 percent of transactions are fraud. What is the simplest model with that score, and which metric would expose it?
A way to think about it
Write the confusion matrix of a model that always predicts not fraud. Then compute its recall.
- Lowering the threshold from 0.5 to 0.3 changes precision and recall but not ROC AUC. Why?
A way to think about it
Look at what each metric uses: the labels after the cut, or only the order of the scores. Ask which of those the threshold touches.
- Two models have the same AUC. One has a much lower log loss. What does the better one do differently, and when would you care?
A way to think about it
AUC keeps only the ordering. Think of multiplying every score by 0.1: the order is unchanged, but are the numbers still believable as probabilities?
- Why is F1 a harmonic mean and not the ordinary average of precision and recall?
A way to think about it
Try precision 1.0 and recall 0.02 in both formulas. Decide which result better describes a model that finds 2 percent of the cases.
- A regression model has an of on the test set. Is that a bug in the metric? What does it mean?
A way to think about it
Compare the model's squared error with that of always predicting the mean of the test targets. The ratio in the formula can exceed 1.