Sign in

Metrics

Evaluation metrics for classification and regression

Classification and regression metrics computed from first principles: confusion matrix, precision, recall, F1, ROC AUC, log loss, MSE, MAE and R squared.

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

  1. Choose the task in the config: binary (labels 0 and 1), multiclass (labels 0 to k−1k - 1) or regression.
  2. Call Metrics.compute with the true labels and predicted labels, predicted scores, or both. Without labels, binary scores at or above threshold become class 1.
  3. For classification, count each pair of true class and predicted class into the confusion matrix.
  4. Read precision, recall and F1 off the matrix, per class or averaged (macro, weighted or micro).
  5. From the scores, compute ROC AUC by ranking, and log loss from the probability given to the true class.
  6. For regression, compute MSE, RMSE, MAE and R2R^2 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.
  • R2R^2 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

IfUse instead
You need to know how stable the number is across different splitsThe holdout and cross-validation evaluation lesson
The output is a ranked list, as in search or recommendationRanking metrics such as NDCG or recall at k
The model is unsupervised and there are no labelsMeasures such as reconstruction error for an Autoencoder or topic coherence for LDA

Math foundations

  1. Accuracy

    accuracy=TP+TNTP+TN+FP+FN\text{accuracy} = \frac{TP + TN}{TP + TN + FP + FN}

    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.

  2. Precision and recall

    precision=TPTP+FP,recall=TPTP+FN\text{precision} = \frac{TP}{TP + FP}, \qquad \text{recall} = \frac{TP}{TP + FN}

    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.

  3. F1 score

    F1=2⋅precision⋅recallprecision+recallF_1 = \frac{2 \cdot \text{precision} \cdot \text{recall}}{\text{precision} + \text{recall}}

    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.

  4. ROC AUC by ranks

    AUC=R+−12 n+(n++1)n+ n−\text{AUC} = \frac{R_{+} - \tfrac{1}{2}\, n_{+}(n_{+} + 1)}{n_{+}\, n_{-}}

    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.

  5. Log loss

    log loss=−1n∑i=1nln⁡pi, yi\text{log loss} = -\frac{1}{n} \sum_{i=1}^{n} \ln p_{i,\,y_i}

    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.

  6. Squared and absolute error

    MSE=1n∑i=1n(yi−y^i)2,RMSE=MSE,MAE=1n∑i=1n∣yi−y^i∣\text{MSE} = \frac{1}{n} \sum_{i=1}^{n} (y_i - \hat{y}_i)^2, \qquad \text{RMSE} = \sqrt{\text{MSE}}, \qquad \text{MAE} = \frac{1}{n} \sum_{i=1}^{n} |y_i - \hat{y}_i|

    Regression errors. Squaring makes large misses count much more than small ones. RMSE and MAE are in the units of the target.

  7. Coefficient of determination

    R2=1−∑i(yi−y^i)2∑i(yi−yˉ)2R^2 = 1 - \frac{\sum_i (y_i - \hat{y}_i)^2}{\sum_i (y_i - \bar{y})^2}

    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

TP, TNTP,\, TN
true positives and true negatives
FP, FNFP,\, FN
false positives and false negatives
n+, n−n_{+},\, n_{-}
number of positive and negative samples
R+R_{+}
sum of the ranks of the positive samples
pi, yip_{i,\,y_i}
probability the model gave to the true class of sample i
yi, y^iy_i,\, \hat{y}_i
target and prediction for sample i
yˉ\bar{y}
mean of the targets
nn
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 TP=1TP = 1, FN=1FN = 1, FP=0FP = 0, TN=2TN = 2. The score ranks are 1, 3, 2, 4.

accuracy=1+24=0.75\text{accuracy} = \frac{1 + 2}{4} = 0.75
precision=11+0=1,recall=11+1=0.5\text{precision} = \frac{1}{1 + 0} = 1, \qquad \text{recall} = \frac{1}{1 + 1} = 0.5
F1=2×1×0.51+0.5=0.667F_1 = \frac{2 \times 1 \times 0.5}{1 + 0.5} = 0.667
R+=2+4=6,AUC=6−12×2×32×2=34=0.75R_{+} = 2 + 4 = 6, \qquad \text{AUC} = \frac{6 - \tfrac{1}{2} \times 2 \times 3}{2 \times 2} = \frac{3}{4} = 0.75

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.75
Read 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

  1. 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.

  2. 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.

  3. 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?

  4. 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.

  5. A regression model has an R2R^2 of −0.3-0.3 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.