Skip to main content

Hands-on: create an ML model

Why This Matters

Testers who have trained a model once ask better questions about every model after it. You will see how little code a model is, how much of the work is the data, and how a model can learn a rule that is almost right. That last part is the reason ML systems need testers.

What you will learn

  • Go through the ML workflow in code: data, features and label, split, train, evaluate
  • Compare a model with a baseline, so a score means something
  • Look inside a simple model and compare what it learned with the real rule

Syllabus: HO-3.1.3 (create an ML model).

The task

The practice loan model decides whether an applicant gets a loan. Its training data is on practiceautomatedtesting.com: 50 past applications with age, income, credit score, city and the decision that was taken (approved: Yes or No). In this lesson you train your own model on that data, and then test it.

The bank’s real rule is simple: approve when the credit score is above 650 and the income is above $50,000. Your model is not told that rule. It has to find it in 50 examples, and some of those examples are wrong on purpose.

You continue in the practice project from the lesson Set up your practice project. Activate the environment first:

cd ai-testing-practice
source .venv/bin/activate          # Windows: .venv\Scripts\activate

The workflow in code

Create the folder module-3 with the file module-3/test_first_model.py. You will build it in five steps; the complete file is at the end of this section.

1. Get the data

import pandas as pd
import pytest
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier, export_text

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


@pytest.fixture(scope="module")
def loans(api):
    """The training data of the loan model: 50 applications, with defects on purpose."""
    response = api.get(f"{api.base}/datasets/loans-train", timeout=10)
    response.raise_for_status()
    return pd.DataFrame(response.json()["data"])

A pandas DataFrame is a table: one row per application, one column per field. The features are the columns the model may use to decide; the label is the answer it has to learn to predict. name and city are left out on purpose: a loan decision should not depend on someone’s name, and module 6 shows what happens when it does.

2. Clean just enough

The dataset contains missing values, an age written as the text "thirty-five", an age of 150, a negative income and duplicate rows. A model cannot train on text where it expects numbers, so remove the worst problems:

def quick_clean(df):
    """Just enough cleaning to train on. The lesson "Data preparation" does this properly."""
    df = df.copy()
    df["age"] = pd.to_numeric(df["age"], errors="coerce")       # "thirty-five" becomes NaN
    df = df.dropna(subset=FEATURES)                               # missing values
    df = df[df["age"].between(18, 120) & (df["income"] >= 0)]     # impossible values
    return df.drop_duplicates(subset=[c for c in df.columns if c != "id"])

This drops 9 of the 50 rows. Throwing data away is the quick fix; the lesson Data preparation and module 6 look at better ones, and at the defects this function does not catch.

3. Split into training and test data

@pytest.fixture(scope="module")
def trained(loans):
    data = quick_clean(loans)
    X_train, X_test, y_train, y_test = train_test_split(
        data[FEATURES], data[LABEL], test_size=0.3, random_state=42, stratify=data[LABEL]
    )

The model learns from the training data and is judged on the test data, which it has never seen. Testing a model on the data it learned from is like grading students on questions they saw the answers to. stratify keeps the share of Yes and No the same in both parts; random_state makes the split the same on every run, so your results match this lesson.

A real project uses a third set, the validation data, to compare and tune models, and keeps the test data for one final test. With 41 usable rows that is too few to split three ways, so this lesson keeps it to two; the lesson Training, validation and test data adds validation with cross-validation and shows why evaluating and testing give different numbers.

4. Train

    model = DecisionTreeClassifier(max_depth=2, random_state=0).fit(X_train, y_train)
    print(f"\n{len(X_train)} rows to train on, {len(X_test)} to test with")
    print(export_text(model, feature_names=FEATURES))
    return model, X_test, y_test

A decision tree learns a series of yes/no questions about the features. max_depth=2 allows at most two questions in a row, which keeps the model small enough to read. fit is the training: one line.

5. Test what it learned

def test_the_model_beats_always_saying_no(trained):
    model, X_test, y_test = trained
    accuracy = accuracy_score(y_test, model.predict(X_test))
    baseline = (y_test == "No").mean()   # a "model" that rejects everyone
    print(f"accuracy {accuracy:.3f}, baseline {baseline:.3f}")
    assert accuracy > baseline


def test_the_model_uses_credit_score_and_income_not_age(trained):
    model, _, _ = trained
    used = {FEATURES[i] for i in model.tree_.feature if i >= 0}
    assert used == {"creditScore", "income"}


@pytest.mark.parametrize(
    "applicant, expected",
    [
        ({"age": 40, "income": 80000, "creditScore": 720}, "Yes"),
        ({"age": 40, "income": 30000, "creditScore": 550}, "No"),
    ],
)
def test_clear_cases_get_the_obvious_decision(trained, applicant, expected):
    model, _, _ = trained
    assert model.predict(pd.DataFrame([applicant]))[0] == expected

Three different kinds of test, and each one asks something else:

  • Better than a baseline. Most applications in the data were rejected, so a “model” that always says No is already right 77% of the time. An accuracy only means something next to the baseline.
  • The right inputs. The tree should base its decision on credit score and income, the inputs the real rule uses, and not on age.
  • Obvious cases. Whatever the model learned, a clearly good and a clearly bad applicant must get the obvious answer. These are cheap tests that catch a model that is completely off.

Run it

pytest module-3 -v -s

-s shows what the tests print. The output:

module-3/test_first_model.py::test_the_model_beats_always_saying_no
28 rows to train on, 13 to test with
|--- creditScore <= 669.50
|   |--- creditScore <= 643.50
|   |   |--- class: No
|   |--- creditScore >  643.50
|   |   |--- class: No
|--- creditScore >  669.50
|   |--- income <= 46947.50
|   |   |--- class: No
|   |--- income >  46947.50
|   |   |--- class: Yes

accuracy 0.846, baseline 0.769
PASSED
module-3/test_first_model.py::test_the_model_uses_credit_score_and_income_not_age PASSED
module-3/test_first_model.py::test_clear_cases_get_the_obvious_decision[applicant0-Yes] PASSED
module-3/test_first_model.py::test_clear_cases_get_the_obvious_decision[applicant1-No] PASSED

============================== 4 passed

What the model learned

Read the tree from the top: if the credit score is above 669.50 and the income is above $46,947.50, approve; otherwise reject. (The first split into 643.50 ends in “No” on both sides; the tree made a question that does not change the answer.)

Compare it with the real rule:

Real ruleLearned
Credit scoreabove 650above 669.50
Incomeabove $50,000above $46,947.50

Close, and wrong. An applicant with a credit score of 660 and an income of $60,000 meets the bank’s rule, and the model rejects them. An applicant with an income of $48,000 does not meet the rule, and the model approves them if their credit score is high enough. Every test above passed anyway.

That is the central problem of testing ML systems in one example. The model learned from 28 examples, and it placed its boundaries somewhere between the examples it happened to see; nobody wrote those numbers down, and the tests that look at overall accuracy cannot see them. You find them by looking at the boundaries themselves: boundary value analysis, which you know from conventional testing, works on models too. Module 7 does it systematically with metamorphic and adversarial testing.

Exercise

  1. Add a test for the boundary: an applicant with credit score 660, income $60,000 and age 40 should be approved under the bank’s rule. Does your test pass?
  2. Change max_depth=2 into max_depth=None (no limit) and run pytest module-3 -v -s again. What happens to the tree and to the accuracy? Is the bigger model better?
Show suggested answer
  1. Add a third case to the parametrize list:

    ({"age": 40, "income": 60000, "creditScore": 660}, "Yes"),
    

    It fails: the model says No, because it only approves above 669.50. The test is right and the model is wrong. In a real project this is a finding for the team that trains the model, with exactly this applicant as the evidence.

  2. Without a depth limit the tree grows until it classifies every training row correctly. Training accuracy goes to 1.0, and test accuracy rises to 0.923 on this split. Better? Not clearly: 0.923 on 13 test rows is one more correct answer than 0.846. A tree that is perfect on its training data has learned the noise too, including the row that is labelled wrongly on purpose. That is overfitting, the subject of the lesson Overfitting and underfitting in module 7, and why the test set, not the training score, is what you report.

Your project so far

ai-testing-practice/
├── .venv/
├── .gitignore
├── conftest.py
├── pytest.ini
├── requirements.txt
├── setup/
│   └── test_setup.py
└── module-3/
    └── test_first_model.py    new in this lesson

The finished version is in the example repository: module-3/test_first_model.py.