Sub topic 7
Testing Model Behavior: Shape, Probabilities, and Invariance
Assume you know Python, pytest, and the basic scikit-learn estimator interface. This chapter focuses on behavioral tests: tests that check what a trained model does, rather than how its internal code is written.
A model can pass unit tests and still produce invalid outputs. For example, a classifier might return the wrong number of rows, probabilities that do not sum to one, or predictions that change when the input rows are reordered. Behavioral tests catch these failures at the model boundary.
What model behavior should remain true?
A useful model test checks a property that should hold for many valid inputs.
Common properties include:
- Output shape: one prediction exists for every input row.
- Probability validity: probabilities are finite, within the range 0 to 1, and sum to 1 for each row.
- Class consistency: the probability columns match the model's known classes.
- Invariance: harmless changes, such as reordering rows, do not change the result for each individual row.
- Failure behavior: invalid input is rejected clearly instead of producing a misleading result.
These tests do not prove that the model is accurate. They prove that the model behaves according to its interface and design.
Test output shape and probabilities
The following example trains a small, deterministic classifier. The fixed random state makes the generated data repeatable. The tests then verify the model's public behavior.
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,
n_informative=3,
n_redundant=0,
random_state=0,
)
model = LogisticRegression(max_iter=200, random_state=0)
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.isfinite(proba).all()
assert (proba >= 0).all()
assert (proba <= 1).all()
assert np.allclose(proba.sum(axis=1), 1.0)
def test_predictions_have_one_value_per_row():
model, X = train_small_model()
predictions = model.predict(X)
assert predictions.shape == (len(X),)np.allclose is preferable to == for floating-point values. Small rounding differences can occur even when the calculation is correct.
The expected shape depends on the model interface. A binary classifier usually returns a one-dimensional array from predict and two probability columns from predict_proba. A multilabel model may use a two-dimensional prediction array instead. Test the contract your application actually uses.
> callout note > Do not test an accidental implementation detail. Test a behavior that downstream code relies on, such as the number of rows, valid probability ranges, or a documented class order.
Test invariance under row reordering
A model should associate each prediction with the corresponding input row. Reordering the rows must reorder the predictions in the same way. It must not change which prediction belongs to a particular row.
def test_predictions_do_not_depend_on_row_order():
model, X = train_small_model()
permutation = np.random.default_rng(0).permutation(len(X))
original_predictions = model.predict(X)
reordered_predictions = model.predict(X[permutation])
assert np.array_equal(
original_predictions[permutation],
reordered_predictions,
)This test uses a seeded random generator, so the permutation is repeatable. The comparison aligns predictions by row identity. Comparing original_predictions directly with reordered_predictions would be incorrect because their positions differ.
Choosing useful behavioral tests
Keep these tests small and focused. A failure should explain which contract broke. Good tests usually avoid large training datasets and expensive hyperparameter searches. They should run on every pull request.
You can add tests for:
- predictions containing only known class labels;
- stable output when the same input is scored twice;
- rejection of the wrong number of features;
- finite outputs for boundary-value inputs;
- consistent behavior after saving and loading the model.
Behavioral tests complement accuracy tests. A model can produce valid probabilities but still perform poorly, so accuracy or other quality thresholds belong in a separate quality-gate test.
Exercise
Why does the row-reordering test compare originalpredictions[permutation] with reorderedpredictions instead of comparing the two arrays directly?
Show answer
Reordering the input rows should reorder the output positions by the same permutation. Indexing the original predictions aligns each prediction with the same input row before comparison.