Evaluating Models: Metrics
An evaluation metric is a number that measures how well a model's predictions match reality. Accuracy is the obvious one, but it often hides what matters. When only 14% of families pay late, a model can be 86% accurate while catching nobody. Choosing the right metric is choosing what "good" means for your decision.
The Confusion Matrix
A confusion matrix counts the four possible outcomes of a yes/no prediction. Here "positive" means "paid late".
| Predicted late | Predicted on time | |
|---|---|---|
| Really late | True positive (TP): caught | False negative (FN): missed |
| Really on time | False positive (FP): false alarm | True negative (TN): correctly left alone |
Example: Classification Metrics
This program measures the logistic regression from "Logistic Regression and Classification" on the 250 test families, at two thresholds. This program uses payments_history.csv from "Supervised Learning".
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import (accuracy_score, confusion_matrix, f1_score, precision_score,
recall_score, roc_auc_score)
from sklearn.model_selection import train_test_split
data = pd.read_csv("payments_history.csv")
X, y = data.drop(columns="late"), data["late"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42, stratify=y)
model = LogisticRegression(max_iter=1000).fit(X_train, y_train)
chance = model.predict_proba(X_test)[:, 1] # the model's chance that each family pays late
for threshold in [0.5, 0.3]:
predicted = (chance >= threshold).astype(int)
tn, fp, fn, tp = confusion_matrix(y_test, predicted).ravel()
print(f"Threshold {threshold}: TP {tp} FP {fp} FN {fn} TN {tn}")
print(f" accuracy {accuracy_score(y_test, predicted):.3f} precision {precision_score(y_test, predicted):.3f}"
f" recall {recall_score(y_test, predicted):.3f} F1 {f1_score(y_test, predicted):.3f}")
print(f"ROC AUC (all thresholds at once): {roc_auc_score(y_test, chance):.3f}")Threshold 0.5: TP 14 FP 4 FN 22 TN 210
accuracy 0.896 precision 0.778 recall 0.389 F1 0.519
Threshold 0.3: TP 22 FP 13 FN 14 TN 201
accuracy 0.892 precision 0.629 recall 0.611 F1 0.620
ROC AUC (all thresholds at once): 0.878Explanation: confusion_matrix(...).ravel() returns the four counts in the order TN, FP, FN, TP. There are 36 late payers in the test set.
- At threshold 0.5, the model flags 18 families and 14 really are late, so precision is 14 / 18 = 0.778. But it catches only 14 of the 36 late payers, so recall is 14 / 36 = 0.389.
- At threshold 0.3, it flags more families: recall rises to 0.611 (22 caught) and precision falls to 0.629, because 13 on-time families are now flagged too.
- Accuracy barely changes (0.896 to 0.892), even though the model's behavior changed a lot. That is why accuracy alone is not enough.
- F1 combines precision and recall, and prefers 0.3 here (0.620 against 0.519).
- ROC AUC of 0.878 measures how well the model's chances rank late payers above on-time ones, across every threshold at once.
Classification Metrics
| Metric | Formula | Question it answers |
|---|---|---|
| Accuracy | (TP + TN) / all | How many predictions were right? |
| Precision | TP / (TP + FP) | Of the families flagged, how many were really late? |
| Recall | TP / (TP + FN) | Of the late families, how many were caught? |
| F1 | 2 × precision × recall / (precision + recall) | One balance of precision and recall |
| ROC AUC | Area under the curve of recall against false-alarm rate | How well are positives ranked above negatives? 0.5 is guessing, 1.0 is perfect |
Example: Regression Metrics
For numbers, the error is the distance between predicted and real values. This program measures the house-price model from "Linear Regression" against a baseline that always predicts the average price. It uses houses.csv from that lesson.
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
from sklearn.model_selection import train_test_split
houses = pd.read_csv("houses.csv")
X, y = houses.drop(columns="price"), houses["price"] # price in thousands of dollars
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42)
predictions = {
"Always the average price": np.full(len(y_test), y_train.mean()), # a baseline
"Linear regression": LinearRegression().fit(X_train, y_train).predict(X_test),
}
for name, predicted in predictions.items():
print(f"{name:25} MAE {mean_absolute_error(y_test, predicted):5.1f}k "
f"RMSE {np.sqrt(mean_squared_error(y_test, predicted)):5.1f}k R² {r2_score(y_test, predicted):6.3f}")Always the average price MAE 89.6k RMSE 104.5k R² -0.020
Linear regression MAE 18.5k RMSE 22.0k R² 0.955Explanation: Prices are in thousands of dollars. The linear regression is off by $18.5k on average (MAE), against $89.6k for the baseline. RMSE ($22.0k) is a little higher than MAE because squaring makes big errors count more. R² of 0.955 means the model explains about 96% of the variation in price; the baseline scores about 0 (slightly below, −0.020, because the training average differs a little from the test average).
| Metric | Description | Units |
|---|---|---|
| MAE | It is used to give the average size of the errors | Same as the target ($k) |
| RMSE | It is used to give an average that punishes big errors more | Same as the target ($k) |
| R² | It is used to give the share of variation explained; 1 is perfect, 0 is no better than the average | None |
Choosing a Metric
| Situation | Metric to watch |
|---|---|
| Missing a positive is costly (a late payer, a disease) | Recall |
| A false alarm is costly (bothering families, blocking payments) | Precision |
| Both matter | F1, or precision and recall side by side |
| Comparing models before choosing a threshold | ROC AUC |
| Prices and amounts | MAE (simple) or RMSE (if big errors matter more) |
Common Mistakes
Reporting accuracy on imbalanced data. Show the confusion matrix and recall for the rare class.
Comparing metrics from different test sets. Compare models on the same data.
Forgetting the threshold. Precision and recall depend on it; ROC AUC doesn't.
Ignoring the baseline. An MAE means little until you know what guessing the average scores.
Interview Corner
What is the difference between precision and recall?
Precision is the share of predicted positives that are real; recall is the share of real positives that were predicted. Lowering the threshold usually raises recall and lowers precision.
When would you use ROC AUC?
To compare how well models rank positives above negatives, independent of any one threshold. Choose the threshold afterwards, based on the costs of each kind of mistake.
Practice
Exercise: a threshold table. Extend the loop to thresholds 0.2, 0.3, 0.4 and 0.5. Which threshold would you choose if each missed late payer costs the school $10 in follow-up, and each false alarm costs $2 in staff time?
Check your understanding:
- Why does accuracy barely change between the two thresholds?
- What is the precision at threshold 0.5, and how is it computed?
- Why is RMSE higher than MAE?
Key Takeaways
Quick reference
| Need | Code |
|---|---|
| Confusion matrix | confusion_matrix(y_test, predicted) |
| Precision, recall, F1 | precision_score, recall_score, f1_score |
| ROC AUC | roc_auc_score(y_test, chances) |
| MAE, RMSE | mean_absolute_error, np.sqrt(mean_squared_error(...)) |
| R² | r2_score(y_test, predicted) |
Was this tutorial helpful?