Sub topic 2
Picking a metric that reflects the goal
A baseline is only useful if you can score it, and the score only means something if the metric matches what you care about. This chapter covers how to choose a metric before you compare any models. It assumes you know supervised learning basics, common metrics (accuracy, precision, recall, mean absolute error), basic scikit-learn, and the idea of a standard error.
Why the metric comes first
A metric turns predictions into one number. Every later decision depends on that number: which baseline is hard to beat, whether a candidate is better, and whether the model is good enough to ship. If you pick the metric after seeing results, you will tend to pick the one that makes your model look best. Fix the metric before you build the first baseline.
A useful metric has three properties:
- It reflects the cost of errors in the real task, not just how often errors occur.
- It is computed on data the model has not seen (see the next chapter on splits).
- It can be explained to the people who decide whether to ship.
Start from the decision, not the model
Ask what happens after a prediction is made. A fraud score might send a transaction to a human reviewer. A demand forecast might set how much stock to order. Each use implies which errors hurt most.
- Name the action that follows the prediction.
- List the ways the prediction can be wrong.
- Estimate what each kind of error costs, even roughly.
- Choose the metric that weights errors in line with those costs.
Classification metrics
Accuracy and class imbalance
Accuracy is the fraction of correct predictions. It is fine when classes are roughly balanced and both error types cost about the same. With imbalanced classes it misleads. If 95% of cases are negative, a model that always predicts "negative" is 95% accurate and never finds a single positive.
The example below builds a majority-class baseline on such data and scores it two ways. Balanced accuracy is the average of recall over the classes, so a constant predictor scores 0.5 on a two-class problem.
from sklearn.datasets import make_classification
from sklearn.dummy import DummyClassifier
from sklearn.metrics import accuracy_score, balanced_accuracy_score
from sklearn.model_selection import train_test_split
X, y = make_classification(n_samples=2000, weights=[0.95, 0.05], random_state=0)
X_train, X_test, y_train, y_test = train_test_split(
X, y, stratify=y, random_state=0
)
baseline = DummyClassifier(strategy="most_frequent").fit(X_train, y_train)
pred = baseline.predict(X_test)
print("accuracy:", accuracy_score(y_test, pred))
print("balanced accuracy:", balanced_accuracy_score(y_test, pred))Accuracy comes out near 0.95 and balanced accuracy at 0.5. The baseline looks strong on one metric and useless on the other. The lesson is that the metric must be chosen before a score is called good.
Precision, recall and F1
Precision is the share of predicted positives that are truly positive. Recall is the share of true positives the model finds. They pull against each other as you move the decision threshold. F1 is their harmonic mean and is a reasonable single number when both matter equally. Often they do not matter equally:
- A cancer screening step wants high recall, because a missed case is costly and a follow-up test is cheap.
- A system that blocks user accounts wants high precision, because a false block is costly.
Threshold-free and cost-based metrics
Precision, recall and F1 depend on a threshold. Average precision (area under the precision-recall curve) summarises ranking quality across all thresholds and is more informative than ROC AUC when positives are rare. ROC AUC can look good on imbalanced data because the large pool of negatives keeps the false positive rate low.
When you can put numbers on error costs, the most direct metric is expected cost. The example below assumes a missed positive costs 50 units and a false alarm costs 1 unit. It compares three thresholds with the cost of a model that never flags anything.
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import average_precision_score, confusion_matrix
from sklearn.model_selection import train_test_split
X, y = make_classification(n_samples=2000, weights=[0.95, 0.05], random_state=0)
X_train, X_test, y_train, y_test = train_test_split(
X, y, stratify=y, random_state=0
)
model = LogisticRegression(max_iter=1000).fit(X_train, y_train)
scores = model.predict_proba(X_test)[:, 1]
COST_FN = 50 # a missed positive
COST_FP = 1 # a false alarm
print("average precision:", round(average_precision_score(y_test, scores), 3))
print("cost of never flagging:", COST_FN * int(y_test.sum()))
for threshold in [0.5, 0.2, 0.1]:
pred = (scores >= threshold).astype(int)
tn, fp, fn, tp = confusion_matrix(y_test, pred, labels=[0, 1]).ravel()
cost = COST_FN * fn + COST_FP * fp
print(f"threshold {threshold}: fn={fn} fp={fp} cost={cost}")Because a miss costs 50 times a false alarm, the cheapest threshold is usually lower than 0.5. The default threshold is rarely the best one. Choosing the threshold on the validation data is part of choosing the metric, and you should report which threshold you used.
Regression and forecasting metrics
Regression metrics differ in how they treat large errors and scale.
| Metric | What it measures | Use it when | Watch out for |
|---|---|---|---|
| MAE | Average absolute error, in target units | Errors cost in proportion to their size | Hides rare large misses |
| RMSE | Square root of the mean squared error | Large errors are disproportionately bad | One outlier can dominate the score |
| MAPE | Average percentage error | Relative error matters | Undefined at zero, biased toward under-prediction |
| R² | Share of variance explained | You want a unitless comparison to the mean | Says nothing about error in real units |
MAE and RMSE are both in the target's units, so they are easy to explain. Report the one that matches your costs. If a 10-unit miss is twice as bad as a 5-unit miss, use MAE. If it is four times as bad, RMSE is closer.
For time series, compare errors against the naive forecast, which predicts that the next value equals the current one. Mean absolute scaled error (MASE) divides your model's MAE by the naive forecast's MAE on the training data. A MASE below 1 means you beat the naive forecast. Score on a period after the training period, never on shuffled rows.
Common mistakes
- Optimising a proxy. Cross-entropy loss is a good training objective, but stakeholders care about missed cases or money. Train on the loss, evaluate on the business metric.
- Changing metrics midway. If a candidate loses on the agreed metric and you switch to one it wins on, the comparison is no longer fair. Record the metric before running experiments.
- Using one number only. A single score hides how the model fails. Pair the headline metric with a confusion matrix or error distribution. Later chapters return to slices and error analysis.
- Scoring on the training data. Training scores are optimistic. Use held-out data for every reported number.
- Ignoring the metric's noise. A metric computed on few positives is unstable. With 20 positives in the test set, one extra hit moves recall by 5 points.
How the metric connects to baselines
Every baseline in the chapters ahead is scored with the metric you choose here. A majority-class predictor, a constant median, a naive forecast and a linear model are all comparable only if they share the metric, the data split and the threshold rule. The metric also sets what "good enough" can mean: a requirement such as "recall above 0.9 at precision above 0.8" is a target on the metric, not a statement about the model.
Exercise
A model flags fraudulent transactions. About 1% of transactions are fraud. A review team can check a limited number of flagged transactions per day, and each missed fraud costs far more than one review. A colleague reports 99% accuracy. Why is this not enough, and what would you report instead?
Show answer
A model that never flags anything is also 99% accurate, so the number says nothing about whether the model finds fraud. Report recall (the share of frauds caught) at the precision the review team can sustain, or average precision, and compare with a baseline that flags nothing or flags at random. If the costs are known, report expected cost at the chosen threshold, with the threshold set on validation data.