Evaluating Models: Metrics

Updated · 7 min read
mediumPython 3.13aimachine-learningmetricsconfusion-matrixprecision-recallscikit-learn

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

Same model, two thresholds: accuracy barely moves, recall jumps
Predicted latePredicted on time
Really lateTrue positive (TP): caughtFalse negative (FN): missed
Really on timeFalse positive (FP): false alarmTrue 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".

Python
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}")
Output
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.878

Explanation: 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

MetricFormulaQuestion it answers
Accuracy(TP + TN) / allHow many predictions were right?
PrecisionTP / (TP + FP)Of the families flagged, how many were really late?
RecallTP / (TP + FN)Of the late families, how many were caught?
F12 × precision × recall / (precision + recall)One balance of precision and recall
ROC AUCArea under the curve of recall against false-alarm rateHow 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.

Python
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}")
Output
Always the average price  MAE  89.6k  RMSE 104.5k  R² -0.020
Linear regression         MAE  18.5k  RMSE  22.0k  R²  0.955

Explanation: 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).

MetricDescriptionUnits
MAEIt is used to give the average size of the errorsSame as the target ($k)
RMSEIt is used to give an average that punishes big errors moreSame as the target ($k)
R²It is used to give the share of variation explained; 1 is perfect, 0 is no better than the averageNone

Choosing a Metric

SituationMetric to watch
Missing a positive is costly (a late payer, a disease)Recall
A false alarm is costly (bothering families, blocking payments)Precision
Both matterF1, or precision and recall side by side
Comparing models before choosing a thresholdROC AUC
Prices and amountsMAE (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:

  1. Why does accuracy barely change between the two thresholds?
  2. What is the precision at threshold 0.5, and how is it computed?
  3. Why is RMSE higher than MAE?

Quick check: metrics

4 questions
1What is a false negative here?
2What happened when the threshold dropped from 0.5 to 0.3?
3What does an MAE of $18.5k mean?
4Which metric ignores the threshold?

Key Takeaways

Quick reference

NeedCode
Confusion matrixconfusion_matrix(y_test, predicted)
Precision, recall, F1precision_score, recall_score, f1_score
ROC AUCroc_auc_score(y_test, chances)
MAE, RMSEmean_absolute_error, np.sqrt(mean_squared_error(...))
R²r2_score(y_test, predicted)

Was this tutorial helpful?

Lesson 129 of 186