Sub topic 2
Validating Data: Schema, Ranges, and Missing Values
This chapter assumes you know pandas DataFrames, pytest, and how to train a scikit-learn classifier. It also assumes a CI service that runs your tests on every pull request.
Checking the schema and ranges
A schema is the set of column names and data types a dataset must have. A range check confirms that values fall within believable limits. Both checks catch upstream breaks, such as a renamed column or a unit change, before they reach training.
Put the checks in one function that returns a list of problems. An empty list means the data passed.
import pandas as pd
EXPECTED_DTYPES = {"age": "int64", "income": "float64", "label": "int64"}
def validate_training_data(df: pd.DataFrame, max_missing: float = 0.05) -> list[str]:
errors = []
for col, dtype in EXPECTED_DTYPES.items():
if col not in df.columns:
errors.append(f"missing column: {col}")
elif str(df[col].dtype) != dtype:
errors.append(f"{col}: expected {dtype}, got {df[col].dtype}")
if "age" in df.columns and not df["age"].between(0, 120).all():
errors.append("age outside [0, 120]")
if len(df) > 0 and df.isna().mean().max() > max_missing:
errors.append(f"missing-value fraction above {max_missing}")
return errorsChecking distributions against a reference
A distribution check compares new data with a saved reference sample. This check measures how far the mean has moved, in units of the reference standard deviation.
def check_drift(current: pd.Series, reference: pd.Series, max_shift: float = 0.5) -> list[str]:
spread = reference.std()
if spread == 0:
return ["reference column has zero spread"]
shift = abs(current.mean() - reference.mean()) / spread
if shift > max_shift:
return [f"mean shifted by {shift:.2f} reference standard deviations"]
return []Testing model behavior
A behavioral test checks properties that any correct model must have, even when accuracy is unknown. Here, probabilities must have the right shape, lie between 0 and 1, and sum to 1 for each row. Predictions must also not depend on row order.
import numpy as np
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
def test_model_behavior():
X, y = make_classification(n_samples=200, n_features=5, random_state=0)
model = LogisticRegression(max_iter=200).fit(X, y)
proba = model.predict_proba(X)
assert proba.shape == (len(X), 2)
assert ((proba >= 0) & (proba <= 1)).all()
assert np.allclose(proba.sum(axis=1), 1.0)
perm = np.random.default_rng(0).permutation(len(X))
assert np.array_equal(model.predict(X)[perm], model.predict(X[perm]))Gating on metrics against a baseline
A quality gate fails the build when a candidate model is below an absolute accuracy floor or drops too far from the current baseline model.
def check_quality_gate(candidate: dict, baseline: dict,
min_accuracy: float = 0.85,
max_drop: float = 0.02) -> list[str]:
failures = []
acc = candidate["accuracy"]
if acc < min_accuracy:
failures.append(f"accuracy {acc:.3f} is below the minimum {min_accuracy:.3f}")
if baseline["accuracy"] - acc > max_drop:
failures.append(f"accuracy dropped more than {max_drop:.3f} from baseline")
return failuresExercise
The schema check passes, but the drift check reports a mean shift of 0.8 standard deviations. Should the build fail, and why?
Show answer
It should fail. The default limit is 0.5, and 0.8 exceeds it. The shift means the new data no longer resembles the reference, so a model trained on it may behave differently in production.