Skip to main content

Hands-on: evaluate a model with metrics

Why This Matters

In lesson 18 you calculated metrics from a confusion matrix someone gave you. In a project, you produce that matrix yourself: you run the model on test data, count, calculate, and then decide whether the numbers are good enough. This lesson does that for the model you built in module 3, and compares it with the bank’s own model.

What you will learn

  • Evaluate a trained model on an independent test set with a framework’s metric functions
  • Check the library’s numbers against the formulas you know
  • Decide which metric matters for the use case, and what a difference between two models is worth

Syllabus: HO-3.3.2 (evaluate an ML model using selected ML functional performance metrics).

The setup

  • Your model: the decision tree of depth 2 from module 3, trained on the prepared loan data from lesson 15.
  • The test set: the 40 applicants from lesson 18, with what actually happened: did they repay the loan? Your model has never seen them. The positive class is repaid.
  • The bank’s model: version 1 of the practice model; its probability per applicant is in the test set. At the production threshold of 0.5 it is the confusion matrix you know from lesson 18: TP 13, FP 3, FN 6, TN 18.

Which metric matters?

Before you calculate anything, decide what you are looking for. For a loan:

  • A false positive is a loan approved for someone who does not repay: the bank loses money. Precision (of the approvals, how many repaid?) measures this.
  • A false negative is a good customer turned away: lost business and an unhappy customer. Recall (of the customers who would repay, how many did we approve?) measures this.

The bank’s acceptance criteria from lesson 18: precision at least 0.80 and recall at least 0.65. Precision is the stricter one, because a bad loan costs more than a missed one. Accuracy is reported, but it is not the criterion.

Hands-on

You continue in the practice project. Create module-4/test_evaluate_model.py:

"""Lesson "Hands-on: evaluate a model with metrics": evaluate your own model on an independent test set."""
import sys
from pathlib import Path

import pandas as pd
import pytest
from sklearn.metrics import accuracy_score, confusion_matrix, f1_score, precision_score, recall_score
from sklearn.tree import DecisionTreeClassifier

sys.path.insert(0, str(Path(__file__).parent.parent / "module-3"))
from test_data_preparation import prepare  # noqa: E402

FEATURES = ["age", "income", "creditScore"]


@pytest.fixture(scope="module")
def my_model(api):
    """Your model from module 3: prepared training data, a decision tree of depth 2."""
    raw = pd.DataFrame(api.get(f"{api.base}/datasets/loans-train", timeout=10).json()["data"])
    train = prepare(raw)
    return DecisionTreeClassifier(max_depth=2, random_state=0).fit(train[FEATURES], train["approved"] == "Yes")


@pytest.fixture(scope="module")
def test_set(api):
    """40 applicants the model has never seen, with the real outcome: did they repay?"""
    return pd.DataFrame(api.get(f"{api.base}/test-set", timeout=10).json()["data"])


def metrics(actual, predicted):
    tp, fn, fp, tn = confusion_matrix(actual, predicted, labels=[True, False]).ravel()
    return {
        "TP": tp, "FP": fp, "FN": fn, "TN": tn,
        "accuracy": accuracy_score(actual, predicted),
        "precision": precision_score(actual, predicted),
        "recall": recall_score(actual, predicted),
        "F1": f1_score(actual, predicted),
    }


def show(name, m):
    print(f"\n  {name:12} TP {m['TP']:2} FP {m['FP']:2} FN {m['FN']:2} TN {m['TN']:2}  "
          f"accuracy {m['accuracy']:.3f}  precision {m['precision']:.3f}  recall {m['recall']:.3f}  F1 {m['F1']:.3f}", end="")

The sys.path line lets you reuse prepare from module 3, so the model is trained on exactly the data you prepared there.

Watch the order in confusion_matrix(...).ravel(). scikit-learn puts the actual classes in rows and the predicted classes in columns, in the order of labels. With labels=[True, False] that gives TP, FN, FP, TN. Get the order wrong and precision and recall silently swap. That is the reason for the first test.

Three tests:

def test_library_metrics_match_the_formulas(my_model, test_set):
    m = metrics(test_set["repaid"], my_model.predict(test_set[FEATURES]))
    tp, fp, fn, tn = m["TP"], m["FP"], m["FN"], m["TN"]
    assert m["accuracy"] == pytest.approx((tp + tn) / (tp + fp + fn + tn))
    assert m["precision"] == pytest.approx(tp / (tp + fp))
    assert m["recall"] == pytest.approx(tp / (tp + fn))
    assert m["F1"] == pytest.approx(2 * m["precision"] * m["recall"] / (m["precision"] + m["recall"]))


def test_my_model_meets_the_acceptance_criteria(my_model, test_set):
    # The bank's criteria: precision at least 0.80 (few loans to people who will not repay),
    # recall at least 0.65 (not too many good customers turned away).
    m = metrics(test_set["repaid"], my_model.predict(test_set[FEATURES]))
    show("my model", m)
    assert m["precision"] >= 0.80
    assert m["recall"] >= 0.65


def test_compare_with_the_banks_model(my_model, test_set):
    mine = metrics(test_set["repaid"], my_model.predict(test_set[FEATURES]))
    bank = metrics(test_set["repaid"], test_set["probability"] >= 0.5)
    show("my model", mine)
    show("bank v1", bank)
    # One applicant more or less is 2.5 percentage points on 40 rows: too few to call a winner.
    assert abs(mine["accuracy"] - bank["accuracy"]) <= 0.05

Run it

pytest module-4/test_evaluate_model.py -v -s
module-4/test_evaluate_model.py::test_library_metrics_match_the_formulas PASSED
module-4/test_evaluate_model.py::test_my_model_meets_the_acceptance_criteria
  my model     TP 14 FP  3 FN  5 TN 18  accuracy 0.800  precision 0.824  recall 0.737  F1 0.778
PASSED
module-4/test_evaluate_model.py::test_compare_with_the_banks_model
  my model     TP 14 FP  3 FN  5 TN 18  accuracy 0.800  precision 0.824  recall 0.737  F1 0.778
  bank v1      TP 13 FP  3 FN  6 TN 18  accuracy 0.775  precision 0.812  recall 0.684  F1 0.743
PASSED

============================== 3 passed

Read the result

Your 30-line model meets the acceptance criteria: precision 0.824 (at least 0.80) and recall 0.737 (at least 0.65).

It also scores a little higher than the bank’s model on every metric. Is it better? The difference is one applicant: your model approves one more customer who repaid (TP 14 instead of 13, FN 5 instead of 6). On 40 test cases, one applicant is 2.5 percentage points of accuracy. With another 40 applicants the order could easily reverse. That is why the comparison test asserts that the difference is small, not that your model wins: on this test set the two models are indistinguishable. Lesson 44 shows how many test cases you need before a difference means something.

Two more things a tester notices:

  • The bank’s model uses gender, name and zip code; yours does not. It reaches the same performance without them. That is a strong argument in a bias discussion (module 6): the sensitive attributes add nothing.
  • Both models make 3 false positives. If the bank wants fewer bad loans, look at those three applicants. Are they similar? That is error analysis, and it often tells you more than the metric.

Exercise

  1. The bank decides that a bad loan costs five times as much as a missed good customer, and raises the precision criterion to 0.90. Does your model pass? What could you change to make it pass, and what would that cost?
  2. Change max_depth=2 to max_depth=None in my_model and run the tests again. What happens to the metrics, and which criterion is affected?
Show suggested answer
  1. No: precision is 0.824. To raise precision you approve fewer, safer applicants: use my_model.predict_proba(...)[:, 1] and approve only when the probability is above a higher threshold, or retrain with stricter settings. The cost is recall: fewer good customers approved. It is the same trade-off you saw with the threshold slider in lesson 18. Whether 0.90 is achievable at an acceptable recall is a question you answer with the test set, before you promise it.

  2. Without a depth limit the tree fits the training data perfectly, including the two wrongly labelled rows, and on the test set it does worse: in lesson 20 you will see accuracy drop from 0.800 to 0.750 with the prepared data. Precision drops below 0.80, so the precision criterion fails. A model that is more complex on the training data is not better on new data: overfitting (lesson 48).

Exam-style questions

Quiz

1. A spam filter is evaluated. Users complain that important e-mails end up in the spam folder. “Spam” is the positive class. Which metric should the tester focus on?

  • A. Recall
  • B. Precision
  • C. Accuracy
  • D. Specificity of the spam class
Show answer
B. Important e-mail marked as spam is a false positive; precision (TP / (TP + FP)) drops when false positives rise.
Quiz

2. Model A has an accuracy of 0.80 and model B of 0.775 on a test set of 40 cases. What is the best conclusion?

  • A. Model A is better
  • B. Model B is better
  • C. The difference is one test case; the test set is too small to conclude that either is better
  • D. Both models fail, because accuracy should be above 0.9
Show answer
C. 2.5 percentage points on 40 cases is a single case. More test data, or a statistical test, is needed.

Your project so far

ai-testing-practice/
├── ...
└── module-4/
    ├── test_metrics.py
    └── test_evaluate_model.py    new in this lesson

The finished version is in the example repository: module-4/test_evaluate_model.py.