Sub topic 7
Testing Model Behavior: Shape, Probabilities, and Invariance
This chapter assumes you can write pytest tests, train a scikit-learn classifier, and read a GitHub Actions workflow. It also assumes you have seen the earlier chapters on code unit tests and data validation. Here you test the trained model itself, using properties it must have no matter how accurate it is.
Why test behavior and not only accuracy
An accuracy number tells you how well a model did on one dataset. It does not tell you whether the model is wired correctly. A model can reach 90% accuracy and still have these problems:
- It returns probabilities that do not sum to 1 because a post-processing step was changed.
- It gives different answers when the same rows arrive in a different order, which points to leakage between rows in a batch.
- It flips its prediction when a feature changes by a rounding error.
- It crashes on a single-row request, even though training ran on thousands of rows.
Behavioral tests catch these bugs. They run in seconds on a small model, so they belong in the fast part of your CI run. They are a different check from the quality gate, which compares metrics against a baseline and is covered in the next chapter.
A behavioral test asserts a property that must hold for any reasonable model of this type. Three families cover most needs:
| Family | Question it answers | Example assertion |
|---|---|---|
| Output contract | Does the model return what callers expect? | Shape is `(n_rows, n_classes)`, no NaN values |
| Probability validity | Are the scores real probabilities? | Each row sums to 1, values lie in [0, 1] |
| Invariance and sensitivity | Does the model respond only to what it should? | Row order does not matter, tiny noise does not flip labels |
Testing a small, seeded model
You do not test your production model in these tests. You train a small model on synthetic data with fixed seeds, so the test is fast and gives the same result every time. The seeding rules come from the reproducibility chapter. Here, random_state=0 fixes the data and default_rng(0) fixes the permutation.
import numpy as np
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
def train_small_model():
X, y = make_classification(n_samples=200, n_features=5, random_state=0)
model = LogisticRegression(max_iter=200)
model.fit(X, y)
return model, X
def test_probabilities_are_valid():
model, X = train_small_model()
proba = model.predict_proba(X)
assert proba.shape == (len(X), 2)
assert np.allclose(proba.sum(axis=1), 1.0)
def test_predictions_do_not_depend_on_row_order():
model, X = train_small_model()
perm = np.random.default_rng(0).permutation(len(X))
assert np.array_equal(model.predict(X)[perm], model.predict(X[perm]))The first test checks the output contract and probability validity together. The shape check guards against a change in the number of classes or in the output layout. The np.allclose check uses a tolerance because floating-point sums of probabilities are rarely exactly 1.0. Never compare them with ==.
The second test is an invariance test. Predicting the rows in shuffled order and then undoing the shuffle must give the same labels as predicting in the original order. Here model.predict(X)[perm] selects the original predictions in shuffled order, and model.predict(X[perm]) predicts on shuffled rows directly. If they differ, something in the prediction path depends on batch position. Typical causes are batch-level normalization applied at inference time, or a stateful preprocessing step that is fitted during prediction.
What the tests do not prove
These tests do not show that the model is good. A model that predicts 0.5 for every row passes both tests. This is intended. Behavioral tests set a floor on correctness, and the quality gate checks how good the model is.
Train once per module, not once per test
The example above retrains the model inside each test. That is fine for 200 rows, but it adds up as the suite grows. A pytest fixture with scope="module" trains once and shares the result:
import numpy as np
import pytest
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
@pytest.fixture(scope="module")
def trained():
X, y = make_classification(n_samples=200, n_features=5, random_state=0)
model = LogisticRegression(max_iter=200).fit(X, y)
return model, X, y
def test_single_row_input(trained):
model, X, _ = trained
proba = model.predict_proba(X[:1])
assert proba.shape == (1, 2)
def test_small_noise_keeps_most_predictions(trained):
model, X, _ = trained
rng = np.random.default_rng(1)
noisy = X + rng.normal(0, 0.01, size=X.shape)
agreement = (model.predict(X) == model.predict(noisy)).mean()
assert agreement >= 0.95A shared fixture has one risk. If a test mutates the model or the arrays, later tests see the change. Treat fixture values as read-only. The tests above build noisy as a new array and never write to X.
The single-row test matters because serving code often sends one row at a time. Bugs such as squeezing a dimension away or reshaping to a fixed batch size show up only with n=1.
Designing invariance and sensitivity tests
Invariance tests assert that an input change should not alter the output. Sensitivity tests assert the opposite: a change should alter the output in a known direction. Pick properties from domain knowledge, not from what the current model happens to do.
Good candidates:
- Row order. Shown above. It applies to almost every model.
- Tiny noise. Adding noise much smaller than the feature's scale should leave nearly all labels unchanged. Test the agreement rate, not exact equality, because a few rows always sit close to the decision boundary.
- Irrelevant fields. An identifier column or a free-text note that the model must ignore can be changed without moving the output.
- Unit conversions. If your feature pipeline converts units, the same physical value in either unit should give the same prediction.
- Directional effects. If domain knowledge says that a higher number of missed payments never lowers default risk, raise that feature and assert that the predicted probability does not decrease. This works best for models with monotonic constraints or for a small set of strong, well-known relationships.
Choosing thresholds
For tolerance-based tests, set the threshold from observation and then leave room. Run the test against the current model several times with different noise seeds. If agreement is always above 0.99, a threshold of 0.95 catches real regressions without failing on harmless changes. A threshold set at the exact observed value makes the test flaky after any dependency update.
Common errors
Exact float comparison. assert proba.sum(axis=1) == 1.0 fails on rounding error. Use np.allclose or pytest.approx.
Unseeded randomness. A test that uses np.random.permutation without a seed passes on most runs and fails on a few. Flaky tests teach a team to ignore red builds. Seed every source of randomness the test touches, including the generator inside make_classification and any model-level random_state.
Testing the library instead of your code. Asserting that scikit-learn's LogisticRegression returns probabilities that sum to 1 tests scikit-learn. The tests earn their place when they wrap your own pipeline: your preprocessing, your post-processing, your calibration step, or your serving wrapper. Point the same assertions at the object your service calls.
Training on tiny data that hides bugs. With 20 rows, a model can behave differently from one trained on 20,000. Keep the sample large enough that every class has a meaningful number of rows, and test the model class and settings you actually deploy.
Overfitting the test to one model. If a test asserts that a particular row gets label 1, any retraining can break it. Assert properties, not individual predictions.
Where these tests run
Behavioral tests belong in the model test layer, after the fast code and data tests. The workflow below runs the code and data tests first, so a broken feature function or a bad sample file fails the build before any model is trained.
name: ml-ci
on:
pull_request:
push:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.11"
cache: pip
- run: pip install -r requirements.txt
- name: Code and data tests
run: pytest tests/unit tests/data -q
- name: Model tests
run: pytest tests/model -qPut the behavioral tests from this chapter in tests/model. Because the model there is small and seeded, the step typically finishes in a few seconds and is cheap enough to run on every pull request.
Summary of the approach
- Train a small, seeded model with the same class and settings as production.
- Assert the output contract: shape, dtype, no NaN values, single-row input.
- Assert probability validity with tolerances.
- Assert invariances that domain knowledge justifies, using agreement rates where exact equality is unrealistic.
- Keep the tests fast and deterministic, and leave the question of how good the model is to the quality gate.
Exercise
A teammate writes assert model.predict(X)[0] == 1 as a behavioral test, using a model trained on the full production dataset loaded from a file. Give two reasons this test is a poor behavioral test and describe a better one.
Show answer
First, it asserts one specific prediction, which changes whenever the model is retrained, so it fails on harmless updates. Second, it depends on an external production artifact and dataset, so the result is not fixed by the commit under review and the test is slow and possibly flaky. A better test trains a small seeded model on synthetic data inside the test and asserts a property, such as predict_proba returning shape (n, n_classes) with rows that sum to 1 under np.allclose, or predictions being unchanged after a seeded row permutation.
Exercise
You add Gaussian noise with standard deviation 0.01 to every feature and require that 100% of predicted labels stay the same. The test passes locally but fails intermittently in CI after a dependency upgrade. What is the likely cause, and how do you fix the test?
Show answer
Some rows lie very close to the decision boundary, so even tiny numeric changes in the upgraded library can flip their labels. Requiring exact equality is too strict. Fix it by asserting an agreement rate, such as (model.predict(X) == model.predict(noisy)).mean() >= 0.95, choosing the threshold from repeated runs with different noise seeds, and keeping the noise generator seeded.