Concept Explanation
A model that scores 99% accuracy on fraud detection is almost certainly useless. If 1 transaction in 100 is fraudulent, a model that predicts "not fraud" every single time — one that has learned nothing at all — scores 99%.
This is not a corner case. It is the single most common way machine learning results are misreported. Choosing the right metric is not a formality after the modelling; it is the modelling decision that determines whether your work is worth anything.
The Confusion Matrix
Every classification metric is derived from four counts:
| Predicted negative | Predicted positive | |
|---|---|---|
| Actually negative | True Negative (TN) | False Positive (FP) |
| Actually positive | False Negative (FN) | True Positive (TP) |
The two errors are not interchangeable, and the domain decides which one hurts:
- Spam filter: an FP puts a real invoice in the junk folder. Expensive.
- Cancer screening: an FN sends a sick patient home. Far worse than a needless follow-up test.
The Metrics
| Metric | Formula | Answers | Use when |
|---|---|---|---|
| Accuracy | (TP+TN)/all | "What fraction did I get right?" | Classes are balanced |
| Precision | TP/(TP+FP) | "When I say positive, am I right?" | False positives are costly |
| Recall | TP/(TP+FN) | "Of all real positives, how many did I catch?" | False negatives are costly |
| F1 | harmonic mean of P and R | One number balancing both | You need a single tie-breaker |
| ROC-AUC | area under TPR/FPR curve | "How well are the classes ranked?" | Comparing models, threshold-free |
| PR-AUC | area under precision/recall curve | Same, but for rare positives | Heavy class imbalance |
Precision and recall trade off against each other. Predict positive more eagerly and recall rises while precision falls. There is no configuration that maximises both; you must decide which error your application can afford.
The Threshold Is Yours to Set
Classifiers do not output classes — they output probabilities. predict() merely applies a 0.5 cut-off, and 0.5 is an arbitrary default that is wrong for most imbalanced problems.
probs = model.predict_proba(X_test)[:, 1]
flagged = probs > 0.25 # catch more positives, accept more false alarms
Tuning this threshold is often the cheapest, largest improvement available to you — no retraining required.
For Regression
| Metric | Reads as | Note |
|---|---|---|
| MAE | Average error, in your units | Robust to outliers; easy to explain |
| RMSE | Like MAE but punishes large misses | Use when big errors are disproportionately bad |
| R² | Fraction of variance explained (0–1) | Can go negative if the model is worse than the mean |
| MAPE | Average error as a percentage | Explodes when true values approach zero |
"The average prediction is off by £12,400" (MAE) communicates far more to a stakeholder than "R² = 0.83".
Cross-Validation
One train/test split on 500 rows gives a score with a wide error bar. K-fold cross-validation trains k times, holding out a different fifth each time, and reports mean plus standard deviation:
scores = cross_val_score(model, X, y, cv=5, scoring="f1")
print(f"{scores.mean():.3f} +/- {scores.std():.3f}")
Use StratifiedKFold for classification so every fold keeps the class balance. For time series, use TimeSeriesSplit — a random split lets the model train on the future and predict the past, which inflates your score and cannot happen in production.
Code Example #1 (Basic)
Why accuracy lies, in one script.
import numpy as np
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.dummy import DummyClassifier
from sklearn.metrics import (accuracy_score, precision_score, recall_score,
f1_score, confusion_matrix, classification_report)
# 2% positives -- realistic fraud-style imbalance
X, y = make_classification(n_samples=5000, n_features=12, n_informative=5,
weights=[0.98, 0.02], random_state=42)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, random_state=42, stratify=y
)
print(f"Positives in test set: {y_test.sum()} of {len(y_test)}\n")
# The model that learned nothing
dummy = DummyClassifier(strategy="most_frequent").fit(X_train, y_train)
d_pred = dummy.predict(X_test)
# A real model
model = LogisticRegression(max_iter=2000).fit(X_train, y_train)
m_pred = model.predict(X_test)
print(f"{'model':<18} {'accuracy':>9} {'precision':>10} {'recall':>8} {'f1':>7}")
for name, pred in [("always-negative", d_pred), ("logistic", m_pred)]:
print(f"{name:<18} "
f"{accuracy_score(y_test, pred):>9.3f} "
f"{precision_score(y_test, pred, zero_division=0):>10.3f} "
f"{recall_score(y_test, pred):>8.3f} "
f"{f1_score(y_test, pred, zero_division=0):>7.3f}")
print("\nThe useless model's accuracy is within a whisker of the real one.")
print("Recall is what separates them.\n")
tn, fp, fn, tp = confusion_matrix(y_test, m_pred).ravel()
print(f"TN={tn} FP={fp} FN={fn} TP={tp}")
print(f"{fn} real positives were missed entirely.\n")
print(classification_report(y_test, m_pred, target_names=["normal", "fraud"]))
The DummyClassifier row is why it belongs in every project. It converts "99% accuracy" from an achievement into a number you can compare against — and the comparison is usually humbling.
Code Example #2 (Intermediate)
Choosing a threshold from the cost of each error, then validating properly.
import numpy as np
import pandas as pd
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split, StratifiedKFold, cross_validate
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import (roc_auc_score, average_precision_score,
precision_recall_curve, roc_curve, confusion_matrix)
X, y = make_classification(n_samples=8000, n_features=20, n_informative=8,
weights=[0.97, 0.03], flip_y=0.01, random_state=7)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=7, stratify=y
)
model = make_pipeline(
StandardScaler(),
RandomForestClassifier(n_estimators=400, class_weight="balanced", random_state=7),
).fit(X_train, y_train)
probs = model.predict_proba(X_test)[:, 1]
# --- Threshold-free ranking quality ---
print(f"ROC-AUC: {roc_auc_score(y_test, probs):.3f}")
print(f"PR-AUC: {average_precision_score(y_test, probs):.3f} <- the honest one when positives are rare")
print(f"Baseline PR-AUC (random) = {y_test.mean():.3f}\n")
# --- Put a price on each error and optimise total cost ---
COST_FP = 5 # a needless manual review
COST_FN = 400 # a fraud that goes through
rows = []
for t in np.arange(0.05, 0.96, 0.05):
pred = (probs >= t).astype(int)
tn, fp, fn, tp = confusion_matrix(y_test, pred).ravel()
rows.append({
"threshold": round(t, 2),
"precision": round(tp / (tp + fp), 3) if tp + fp else 0.0,
"recall": round(tp / (tp + fn), 3) if tp + fn else 0.0,
"FP": fp, "FN": fn,
"cost": fp * COST_FP + fn * COST_FN,
})
table = pd.DataFrame(rows)
print(table.to_string(index=False))
best = table.loc[table["cost"].idxmin()]
print(f"\nCheapest threshold: {best['threshold']} "
f"(cost {int(best['cost'])}, recall {best['recall']})")
print(f"Default 0.50 cost: {int(table.loc[table['threshold'] == 0.5, 'cost'].iloc[0])}")
# --- Cross-validate several metrics at once ---
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=7)
cvres = cross_validate(
model, X_train, y_train, cv=cv,
scoring=["accuracy", "precision", "recall", "f1", "roc_auc", "average_precision"],
)
print("\n5-fold cross-validation on the training set:")
for key in sorted(k for k in cvres if k.startswith("test_")):
vals = cvres[key]
print(f" {key[5:]:<18} {vals.mean():.3f} +/- {vals.std():.3f}")
The cost table is the professional version of this whole lesson. Once each error has a price, "which threshold?" stops being a judgement call and becomes arithmetic — and the answer is almost never 0.5.
Common Mistakes
- Reporting accuracy on imbalanced data: the headline number is dominated by the majority class and hides total failure on the class you care about.
- No baseline: without
DummyClassifier, you cannot tell a good score from an easy dataset. - Accepting the 0.5 threshold: it is a default, not a decision. Choose it from the cost of each error.
- Optimising F1 when the costs are lopsided: F1 weights precision and recall equally. If an FN costs 80× an FP, say so and optimise cost directly.
- Random splits on time series: training on future rows to predict past ones inflates every metric. Use
TimeSeriesSplit. - Tuning on the test set: every peek leaks information. Tune with cross-validation on the training set.
- Using ROC-AUC alone with rare positives: the huge TN count keeps the false-positive rate low, so ROC-AUC stays flattering. PR-AUC does not.
- Quoting only R² for regression: stakeholders understand "off by £12,400 on average". They do not act on 0.83.
- Ignoring the standard deviation from cross-validation: 0.85 ± 0.02 and 0.85 ± 0.14 are very different findings.
- Never printing the confusion matrix: it is four numbers that answer more questions than any single metric.
Best Practices
- Pick the metric before you train, from the question and the cost of each error.
- Always include a
DummyClassifieror mean-predictor baseline in the results table. - Print the confusion matrix and
classification_reportfor every classifier — the per-class breakdown is where problems surface. - Report mean ± std from cross-validation, not a single split.
- Use
StratifiedKFoldfor classification andTimeSeriesSplitfor anything ordered in time. - Prefer PR-AUC over ROC-AUC when positives are under about 10%.
- Sweep the threshold and cost it out: this is free performance you can get without touching the model.
- Report regression error in the target's own units (MAE or RMSE), with R² as a secondary number.
- Lock the test set away and touch it once, after every decision has been made.
- Write down the metric, the baseline, and the threshold alongside the score. A number without those three is not a result.
Practice Exercises
- The 99% Trap: Generate a dataset with
weights=[0.99, 0.01], train aDummyClassifier(strategy="most_frequent"), and print its accuracy, precision, recall, and F1. Write a one-sentence explanation of why accuracy is meaningless here. - The Cost Sweep: Take any imbalanced classifier's
predict_probaoutput, assign your own FP and FN costs, and build a table of total cost across thresholds from 0.05 to 0.95. Report the cheapest threshold and how much it saves over 0.5. - The Fold Comparison: Evaluate the same model with
cross_validateusingKFoldand thenStratifiedKFoldon an imbalanced dataset. Compare the standard deviations and explain why stratifying tightened them.