Sub topic 1
Why CI for ML is different: code, data, and models can all break
Continuous integration (CI) is a service that runs your checks automatically whenever someone changes the project. In a machine learning project, three things can break: the code, the data, and the model. Code breaks when a function changes behavior. Data breaks when a file arrives with a missing column or unexpected values. A model breaks when its accuracy drops, even though every code test still passes.
Prerequisites
This chapter assumes you know Python and pytest, use Git with pull requests, have trained a scikit-learn model, and have seen a YAML CI file such as one for GitHub Actions.
A layered test strategy: what to test where
Split your checks into three layers. Each layer catches a different kind of failure.
| Layer | What it checks | Typical runtime |
|---|---|---|
| Code | Functions return correct values and raise errors on bad input | Seconds |
| Data | Schema, value ranges, and missing values | Seconds to minutes |
| Model | Output shape, probability validity, and metric gates | Minutes |
Run the fast code and data layers on every pull request. Run heavy model training on a schedule or on demand.
Making tests reproducible: seeds, pinned dependencies, tolerances
A test that passes on one run and fails on the next wastes time. Three habits prevent this:
- Set random seeds, such as
np.random.default_rng(0), so data sampling and shuffling repeat. - Pin dependency versions in
requirements.txt, such asscikit-learn==1.5.2, so a library update cannot change results silently. - Compare floats with a tolerance, using
pytest.approxornp.allclose, instead of==.
Unit testing feature and preprocessing code
Feature functions are plain Python, so test them like any other function. Include a test for the failure case as well as the normal case.
import pytest
def scale_income(income: float, median: float) -> float:
if median <= 0:
raise ValueError("median must be positive")
return income / median
def test_scale_income_basic():
assert scale_income(50_000.0, 25_000.0) == pytest.approx(2.0)
def test_scale_income_rejects_bad_median():
with pytest.raises(ValueError):
scale_income(50_000.0, 0.0)Save this as tests/unit/test_features.py and run pytest tests/unit -q. Both tests should pass.
Exercise
Why should a test compare a float with pytest.approx instead of ==?
Show answer
Floating-point arithmetic can differ by tiny amounts across machines or library versions, so an exact comparison can fail even when the code is correct. pytest.approx accepts values that are equal within a small tolerance.