Testing ML Code and Models
ML code fails in two ways. Some failures are ordinary bugs: a feature function divides by zero, a join drops rows, a scaler is refitted on test data. Others are failures of the model: it is accurate on average but learned that more debt means less risk, it relies on a customer id, or it is fine overall and poor for customers over 50. Ordinary software tests catch the first kind. The second kind needs tests written against the model's behaviour, because an aggregate metric hides it. Both belong in the same test suite and run in CI on every change.
What to test
| Layer | Tests | Example |
|---|---|---|
| Code: transforms and features | unit tests with small hand-made inputs, edge cases | debt_ratio(500, 2000) == 0.25; zero income; NaN; empty frame |
| Code: pipeline wiring | shapes, dtypes, no rows lost, no mutation of inputs, fit only on training data | the scaler keeps its training mean when transforming new data |
| Data | schema, ranges, nulls, uniqueness, distributions | Data Validation, the next lesson |
| Model: performance | metric thresholds on a fixed held-out set, compared with the current champion | AUC at least 0.70 |
| Model: slices | the metric per segment (age band, region, device) | no age band far below the overall AUC |
| Model: behaviour | minimum functionality, invariance, directional expectation | more debt never lowers the risk |
| Training | a smoke test: train on a small sample for a few steps, loss decreases, artifact saves and loads | runs in CI in seconds |
The behavioural categories come from software testing of NLP models (the CheckList paper by Ribeiro et al., ACL 2020): a minimum functionality test (MFT) checks simple cases with an obvious answer, an invariance test (INV) applies a change that should not affect the prediction, and a directional expectation test (DIR) applies a change that should move the prediction in a known direction.
Unit tests for transforms
The tools: pytest collects functions named test_* and reports their failures. The browser cannot run pytest's command-line runner, so this example uses a ten-line stand-in that does the same thing; in a project you would put the tests in tests/test_features.py and run pytest. The code under test: a debt_ratio feature, a hand-written Standardiser and an add_features function that also bins ages.
import math, traceback
import numpy as np
import pandas as pd
def run_tests(namespace):
"""A tiny stand-in for pytest: call every test_* function, report PASS/FAIL."""
tests = [(n, f) for n, f in namespace.items() if n.startswith("test_") and callable(f)]
failed = 0
for name, fn in tests:
try:
fn()
print(f"PASS {name}")
except AssertionError as e:
failed += 1
print(f"FAIL {name}: {e}")
except Exception as e:
failed += 1
print(f"ERROR {name}: {type(e).__name__}: {e}")
print(f"{len(tests) - failed} passed, {failed} failed")
# --- code under test ---------------------------------------------------------------------------
def debt_ratio(debt, income):
"""Monthly debt payments / monthly income, as a feature."""
return debt / income
class Standardiser:
def fit(self, x):
self.mean_, self.std_ = float(np.mean(x)), float(np.std(x))
return self
def transform(self, x):
return (np.asarray(x, dtype=float) - self.mean_) / (self.std_ if self.std_ > 0 else 1.0)
def add_features(df):
out = df.copy()
out["debt_ratio"] = debt_ratio(out["debt"], out["income"])
out["age_band"] = pd.cut(out["age"], bins=[17, 30, 50, 120], labels=["18-30", "31-50", "51+"])
return out
# --- tests -------------------------------------------------------------------------------------
def test_debt_ratio_simple():
assert debt_ratio(500, 2000) == 0.25
def test_debt_ratio_zero_income_is_finite():
r = debt_ratio(np.array([500.0]), np.array([0.0]))
assert np.isfinite(r).all(), f"got {r.tolist()} for zero income"
def test_standardiser_uses_training_statistics_only():
s = Standardiser().fit([1.0, 2.0, 3.0])
assert math.isclose(s.transform([2.0])[0], 0.0)
assert math.isclose(s.transform([100.0])[0], (100 - 2) / s.std_) # not refitted on new data
def test_standardiser_constant_column():
out = Standardiser().fit([5.0, 5.0]).transform([5.0, 6.0])
assert out.tolist() == [0.0, 1.0], out.tolist()
def test_add_features_keeps_rows_and_does_not_mutate_input():
df = pd.DataFrame({"income": [3000.0, 4500.0], "debt": [600.0, 900.0], "age": [25, 64]})
before = df.copy()
out = add_features(df)
assert len(out) == len(df)
pd.testing.assert_frame_equal(df, before)
assert list(out["age_band"].astype(str)) == ["18-30", "51+"]
def test_add_features_ages_at_band_edges():
out = add_features(pd.DataFrame({"income": [1.0] * 3, "debt": [0.0] * 3, "age": [18, 30, 31]}))
assert out["age_band"].notna().all(), out["age_band"].tolist()
assert list(out["age_band"].astype(str)) == ["18-30", "18-30", "31-50"]
run_tests(dict(globals()))PASS test_debt_ratio_simple
FAIL test_debt_ratio_zero_income_is_finite: got [inf] for zero income
PASS test_standardiser_uses_training_statistics_only
PASS test_standardiser_constant_column
PASS test_add_features_keeps_rows_and_does_not_mutate_input
PASS test_add_features_ages_at_band_edges
5 passed, 1 failed
One test fails: debt_ratio returns inf for an applicant with zero income. NumPy does not raise on division by zero for arrays, so the infinity would have flowed silently into training (where some models fail on it and others treat it as a very large number). The fix is a decision, not just code: return NaN and let the imputer handle it, or cap the ratio, and the test then documents the decision. Notice what the other tests protect:
test_standardiser_uses_training_statistics_onlypins the rule that transforming new data must not refit the statistics (leakage);test_standardiser_constant_columncovers the division by a zero standard deviation;test_add_features_keeps_rows_and_does_not_mutate_inputchecks that a feature function neither loses rows nor changes its input in place (a common pandas bug);test_add_features_ages_at_band_edgeschecks the edges 18, 30 and 31, where off-by-one errors inpd.cutbins live.
Good transform tests are small, use hand-computed expected values, and target edges: zero, negative, missing, empty, the boundaries of bins, unseen categories, extreme values. pd.testing.assert_frame_equal and np.testing.assert_allclose compare frames and arrays with readable failure messages and tolerances.
Model tests: thresholds, slices and behaviour
The data: 4,000 synthetic loan applicants with monthly income, debt ratio, age and a random customer_id, and a default label drawn from a known formula in which risk rises with debt ratio and falls with income and age. 2,800 rows train, 1,200 test (stratified). The test suite has five checks:
- performance threshold: test AUC at least 0.70;
- slices: the worst age band's AUC at most 0.05 below the overall AUC;
- directional expectation: adding 0.1 to
debt_rationever lowers predicted risk; - invariance: shuffling
customer_idchanges no prediction by more than 0.01; - minimum functionality: a high-income, low-debt applicant gets risk below 0.2 and a low-income, high-debt one above 0.6.
Model A is a gradient-boosted tree model on all four columns; model B drops customer_id and uses monotonic constraints (risk may only fall with income and only rise with debt ratio).
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.metrics import roc_auc_score
rng = np.random.default_rng(0)
n = 4000
df = pd.DataFrame({"income": rng.lognormal(8.2, 0.4, n).round(0), # monthly income
"debt_ratio": rng.beta(2, 5, n).round(3),
"age": rng.integers(18, 75, n),
"customer_id": rng.integers(100000, 999999, n)}) # must not matter
logit = -1.0 + 4.0 * df.debt_ratio - 0.0004 * (df.income - 3600) - 0.02 * (df.age - 45)
df["default"] = (rng.random(n) < 1 / (1 + np.exp(-logit))).astype(int)
features = ["income", "debt_ratio", "age", "customer_id"]
tr, te = train_test_split(df, test_size=0.3, random_state=0, stratify=df["default"])
def checks(model, cols):
p = lambda d: model.predict_proba(d[cols])[:, 1]
base = p(te)
results = {}
# 1. performance threshold on the held-out rows
results["AUC >= 0.70"] = (auc := roc_auc_score(te["default"], base)) >= 0.70, f"AUC {auc:.3f}"
# 2. slices: no age band far below the overall AUC
bands = pd.cut(te["age"], [17, 30, 50, 120], labels=["18-30", "31-50", "51+"])
worst = min((roc_auc_score(te["default"][bands == b], base[bands == b]), b) for b in bands.cat.categories)
results["every age band AUC >= overall - 0.05"] = worst[0] >= auc - 0.05, f"worst {worst[1]} {worst[0]:.3f}"
# 3. directional expectation: more debt never lowers the risk
more_debt = te.assign(debt_ratio=te["debt_ratio"] + 0.1)
viol = (p(more_debt) < base - 1e-9).mean()
results["debt_ratio +0.1 never lowers risk"] = viol == 0, f"violated on {viol:.1%} of rows"
# 4. invariance: the customer id must not change the prediction
shuffled = te.assign(customer_id=np.random.default_rng(1).permutation(te["customer_id"].values))
change = np.abs(p(shuffled) - base).max()
results["customer_id does not matter"] = change < 0.01, f"max change {change:.3f}"
# 5. minimum functionality: obvious cases
obvious = pd.DataFrame({"income": [12000, 900], "debt_ratio": [0.02, 0.95], "age": [45, 45],
"customer_id": [500000, 500000]})
po = p(obvious)
results["obvious cases ordered"] = po[0] < 0.2 < 0.6 < po[1], f"low-risk {po[0]:.2f}, high-risk {po[1]:.2f}"
for name, (ok, detail) in results.items():
print(f" {'PASS' if ok else 'FAIL'} {name:38} {detail}")
print(f"rows: train {len(tr)}, test {len(te)}, default rate {df['default'].mean():.3f}")
print("model A: gradient boosting on all four columns")
a = HistGradientBoostingClassifier(max_iter=200, random_state=0).fit(tr[features], tr["default"])
checks(a, features)
print("model B: without customer_id, monotonic in income (-1) and debt_ratio (+1)")
cols = ["income", "debt_ratio", "age"]
b = HistGradientBoostingClassifier(max_iter=200, random_state=0, monotonic_cst=[-1, 1, 0])
b.fit(tr[cols], tr["default"])
checks(b, cols)rows: train 2800, test 1200, default rate 0.509
model A: gradient boosting on all four columns
FAIL AUC >= 0.70 AUC 0.650
PASS every age band AUC >= overall - 0.05 worst 51+ 0.613
FAIL debt_ratio +0.1 never lowers risk violated on 30.3% of rows
FAIL customer_id does not matter max change 0.738
PASS obvious cases ordered low-risk 0.01, high-risk 1.00
model B: without customer_id, monotonic in income (-1) and debt_ratio (+1)
PASS AUC >= 0.70 AUC 0.702
PASS every age band AUC >= overall - 0.05 worst 51+ 0.677
PASS debt_ratio +0.1 never lowers risk violated on 0.0% of rows
PASS customer_id does not matter max change 0.000
PASS obvious cases ordered low-risk 0.00, high-risk 1.00
Model A fails three checks, and the overall metric alone tells only part of the story. Its test AUC is 0.650, below the threshold: with 200 boosting rounds on noisy labels it overfits. More telling are the behavioural failures: on 30.3 % of the test applicants, more debt lowers the predicted risk, and shuffling the customer ids changes some predictions by up to 0.738, so the model has memorised noise in an id column. Neither would show up in a single accuracy number, and both are the kind of behaviour that makes a credit model indefensible. It still passes the minimum functionality test: obvious cases are easy.
Model B passes everything: AUC 0.702, worst age band (51+) at 0.677, no directional violations, and the id cannot matter because it is not an input. The monotonic constraints are domain knowledge turned into model structure, and they also regularise: model B scores higher than model A. The general lesson: write down what the model must and must not do, as tests, before comparing scores.
Where the thresholds come from matters. A fixed 0.70 is a floor for a sanity check; in a release pipeline the main comparison is against the current champion on the same held-out set (The Model Registry), with a tolerance based on the metric's noise. The held-out set for these checks is fixed and versioned, and never used for tuning.
Organising the suite
- Fast tests (units, wiring, data schema, behaviour on a saved small model) run on every commit and finish in seconds.
- Slow tests (training on the full data, full evaluation, slices on large sets) run nightly or in the release pipeline.
- A training smoke test trains on a few hundred rows for a few steps and checks that the loss goes down, the output has the right shape and the artifact can be saved and loaded. It catches most pipeline breakage in seconds.
- In pytest,
@pytest.mark.parametrizeruns one test over many inputs (every slice, every edge value), fixtures share a trained small model between tests, and markers (@pytest.mark.slow) separate fast from slow. Property-based testing (the Hypothesis library) generates many random inputs for invariants such as "the output is always finite and in [0, 1]". - Tests for stochastic training use fixed seeds and tolerances, never exact float equality across machines (reproducibility).
Pitfalls
- Only testing the score. A model can meet the threshold while violating obvious domain rules, as model A's directional failure shows.
- Thresholds tuned until the test passes. A threshold lowered to let a model through is not a test. Decide thresholds before the run, from the champion and the metric's noise.
- Slices too small to test. An AUC on 30 rows is noise; set a minimum slice size, or report the interval instead of a hard threshold.
- Testing on the training data. Behaviour and threshold checks use held-out rows; a model that memorised its training set passes them there.
- Flaky tests from randomness. Unseeded data generation or training makes tests fail now and then, and flaky tests get ignored. Seed everything in tests.
- No test for the fix. When a production incident reveals a behaviour bug, add the failing case as a test first, then fix it.
Practice
- Write the fix for
debt_ratioso that zero income givesNaN, and change the test so that it checks this decision. - Give one invariance test and one directional expectation test for a model that predicts house prices.
- Model A in the example passed the minimum functionality test but failed the directional test. Why is that possible, and which test is more informative?
Answers
return np.where(income > 0, debt / np.where(income > 0, income, 1), np.nan)(the innerwhereavoids the division warning). Test:assert np.isnan(debt_ratio(np.array([500.0]), np.array([0.0])))[0], plus the existing simple case.- Invariance: changing the listing id, the order of the listing photos, or the seller's name should not change the price. Directional: adding a bathroom or increasing the floor area (all else equal) should not decrease the predicted price.
- The MFT checks two extreme applicants, which almost any model ranks correctly. The directional test perturbs 1,200 realistic applicants and found violations on 30.3 % of them, where the model's local behaviour is erratic. The directional test is more informative about how the model behaves on real inputs; the MFT is a cheap first alarm.
Test yourself
A test shuffles the customer_id column and checks that predictions do not change. What kind of test is this?
- Minimum functionality test
- Invariance test
- Directional expectation test
- Performance threshold
Why did test_debt_ratio_zero_income_is_finite fail?
- pytest was missing
- Dividing a NumPy array by zero gives
infwithout raising an error - The test was wrong
- Integer division
What did the monotonic constraints change in the example?
- Nothing
- They removed all directional violations and, together with dropping
customer_id, raised the test AUC from 0.650 to 0.702 - They lowered the AUC
- They made training slower only
Where should the main promotion threshold for a new model come from?
- A fixed number chosen after seeing the results
- A comparison with the current champion on the same fixed held-out set, with a tolerance based on metric noise
- The training accuracy
- The previous model's training loss