Sub topic 9
Choosing evaluation metrics
This chapter assumes you can train a scikit-learn classifier and split data into train and test sets. It also assumes you know what a prediction and a label are. A metric is a number that summarizes how well predictions match the truth. The metric you pick decides which models look good, which ones you tune toward, and whether the model helps the business.
Start from the cost of mistakes
Choose the metric before you train anything, using the problem framing from earlier chapters. Ask what a wrong prediction costs, in each direction.
A binary classifier makes two kinds of errors:
- A false positive is a negative case predicted as positive. Example: a legitimate payment is blocked.
- A false negative is a positive case predicted as negative. Example: a fraudulent payment goes through.
These errors rarely cost the same. The metric should reflect that difference.
The confusion matrix
Every classification metric below comes from four counts:
| Row | Predicted positive | Predicted negative |
|---|---|---|
| Actually positive | True positive (TP) | False negative (FN) |
| Actually negative | False positive (FP) | True negative (TN) |
Classification metrics
| Metric | Formula | Answers the question | Use when |
|---|---|---|---|
| Accuracy | (TP + TN) / all | How often is the model right? | Classes are balanced and errors cost the same |
| Precision | TP / (TP + FP) | Of the cases I flagged, how many were real? | False positives are expensive |
| Recall | TP / (TP + FN) | Of the real cases, how many did I catch? | False negatives are expensive |
| F1 | 2PR / (P + R) | Is there a balance of precision and recall? | You need one number for both and the positive class is rare |
| ROC AUC | Area under the true-positive-rate versus false-positive-rate curve | How well does the model rank positives above negatives? | You compare models across all thresholds |
| Average precision | Area under the precision-recall curve | Same, but focused on the positive class | The positive class is rare |
Why accuracy misleads
Suppose 1% of transactions are fraud. A model that always predicts "not fraud" scores 99% accuracy and catches nothing. Accuracy hides this because the majority class dominates the count. The baseline chapter shows how to measure this with a majority-class model. Always compare your metric against that baseline.
Threshold-based and ranking metrics
Precision, recall, F1 and accuracy depend on a decision threshold. A classifier like logistic regression outputs a probability, and predict turns it into a class by comparing it with 0.5. Moving the threshold trades precision for recall:
- A lower threshold flags more cases. Recall rises and precision usually falls.
- A higher threshold flags fewer cases. Precision usually rises and recall falls.
ROC AUC and average precision do not use a threshold. They score the probabilities themselves, so they measure ranking quality. After you pick a model with a ranking metric, choose the threshold separately, based on the cost of each error.
Computing the metrics
The next example uses the breast cancer dataset. In this dataset label 0 is malignant and label 1 is benign. We want to catch malignant tumors, so we treat malignant as the positive class. We build a 0/1 target where 1 means malignant, and use the probability of class 0.
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import (
average_precision_score,
confusion_matrix,
f1_score,
precision_score,
recall_score,
roc_auc_score,
)
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_breast_cancer(return_X_y=True, as_frame=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=42
)
model = Pipeline([
("scale", StandardScaler()),
("clf", LogisticRegression(max_iter=1000)),
])
model.fit(X_train, y_train)
# Positive class = malignant = label 0.
y_true = (y_test == 0).astype(int)
p_malignant = model.predict_proba(X_test)[:, 0]
print("ROC AUC:", round(roc_auc_score(y_true, p_malignant), 3))
print("Average precision:", round(average_precision_score(y_true, p_malignant), 3))
for threshold in [0.5, 0.3, 0.1]:
y_pred = (p_malignant >= threshold).astype(int)
tn, fp, fn, tp = confusion_matrix(y_true, y_pred).ravel()
print(
f"threshold={threshold}: TP={tp} FP={fp} FN={fn} TN={tn}",
f"precision={precision_score(y_true, y_pred):.3f}",
f"recall={recall_score(y_true, y_pred):.3f}",
f"f1={f1_score(y_true, y_pred):.3f}",
)As the threshold drops, false negatives shrink and false positives grow. In a screening setting, a missed tumor is much worse than an extra follow-up test, so a lower threshold is often the right choice. ROC AUC and average precision stay the same across all three rows because they do not depend on the threshold.
Averaging for more than two classes
With three or more classes, precision, recall and F1 are computed per class and then combined. The average argument controls how:
macrotakes the plain mean of per-class scores. Every class counts equally, so rare classes matter as much as common ones.weightedweights each class by how many true examples it has.micropools all TP, FP and FN counts. For single-label problems it equals accuracy.
If rare classes matter to you, use macro and also inspect classification_report, which prints per-class scores.
Regression metrics
For a numeric target, the common metrics are:
| Metric | What it measures | Notes |
|---|---|---|
| MAE (mean absolute error) | Average size of errors, in target units | Easy to explain, less affected by outliers |
| RMSE (root mean squared error) | Square root of the mean squared error | Punishes large errors more |
| R² | Share of variance explained, compared with always predicting the mean | Can be negative on test data if the model is worse than that mean |
Pick MAE when all errors cost in proportion to their size. Pick RMSE when large errors are disproportionately bad.
Using a metric in model selection
Pass the same metric to cross-validation and tuning with the scoring argument, for example scoring="f1" or scoring="average_precision". If you tune on accuracy and report recall, the tuning optimized the wrong thing.
Scikit-learn scorers follow a "higher is better" rule. Error metrics are therefore exposed as negatives, such as neg_mean_absolute_error. A cross-validation result of -3.2 means an MAE of 3.2.
Common errors
- Reporting accuracy on imbalanced data without a baseline.
- Computing precision or recall for the wrong positive class.
- Using
predictoutputs (0 or 1) for ROC AUC. Pass probabilities or decision scores instead. Hard labels collapse the curve to a single point. - Choosing a threshold on the test set. Choose it on validation data or with cross-validation, then report the test score once.
- Comparing one metric across datasets with different class balance. Precision and average precision depend on how common the positive class is.
- Reporting a single metric. Show the confusion matrix beside it so readers see the error types.
Exercise
A model that screens for a rare disease (1% of patients) has 98% accuracy. Its confusion matrix on 1,000 patients shows TP=2, FP=18, FN=8, TN=972. Compute its precision and recall, and say what the accuracy hides.
Show answer
Precision = 2 / (2 + 18) = 0.10. Recall = 2 / (2 + 8) = 0.20. Accuracy = (2 + 972) / 1000 = 97.4%, which is close to the 99% a model that always predicts "healthy" would score. The accuracy hides that the model finds only 2 of 10 sick patients, and 9 of every 10 alarms are false.
Exercise
You train a fraud classifier and choose the threshold by maximizing F1 on the test set, then report that test F1. What is wrong, and what should you do instead?
Show answer
The threshold was tuned on the test set, so the reported F1 is optimistic because the test data influenced the model's decision rule. Choose the threshold on validation data or through cross-validation on the training set, fix it, then compute the test score once.