Sub topic 5
Validating Data: Schema, Ranges, and Missing Values
Assume you know Python, pandas, pytest, and how a training pipeline loads a CSV file. This chapter focuses on checks that stop malformed data before it reaches feature engineering or model training.
Why data validation belongs in CI
In conventional software, a failing function often causes a visible test failure. In machine learning, the code can run successfully while the input data has changed. A renamed column, an impossible age, or a new pattern of missing values can produce a model that trains but cannot be trusted.
Data validation turns assumptions about training data into executable checks.
A useful data contract describes the expected structure and rules:
| Field | Expected type | Rule |
|---|---|---|
| `age` | integer | Between 0 and 120 |
| `income` | floating point | Missing fraction at most 5% |
| `label` | integer | Must be 0 or 1 |
The validator should report all discovered problems, rather than stopping at the first one. A CI job can then print every failure in one run.
Implementing schema and value checks
The following validator checks required columns, exact pandas data types, an age range, allowed labels, and the maximum missing-value fraction.
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 column, expected_dtype in EXPECTED_DTYPES.items():
if column not in df.columns:
errors.append(f"missing column: {column}")
elif str(df[column].dtype) != expected_dtype:
errors.append(
f"{column}: expected {expected_dtype}, "
f"got {df[column].dtype}"
)
if "age" in df.columns and not df["age"].between(0, 120).all():
errors.append("age outside [0, 120]")
if "label" in df.columns and not df["label"].isin([0, 1]).all():
errors.append("label contains values other than 0 and 1")
if len(df) > 0 and df.isna().mean().max() > max_missing:
errors.append(f"missing-value fraction above {max_missing}")
return errorsThe column check happens before the range and category checks. This avoids trying to validate a field that does not exist. The len(df) > 0 condition also prevents an empty table from producing misleading missing-value results.
Exact dtype checks are useful when the contract is strict, but CSV loading can infer types differently after a data change. For example, a column containing a missing integer may become pandas' nullable Int64 type instead of NumPy's int64. Decide whether that difference matters to your pipeline. If it does not, validate semantic types instead of comparing dtype strings exactly.
Testing the validator
Commit a small representative sample under tests/data/sample.csv. The test below makes the data contract part of the pull-request checks.
import pandas as pd
from validation import validate_training_data
def test_sample_data_is_valid():
df = pd.read_csv("tests/data/sample.csv")
assert validate_training_data(df) == []Add focused tests for each rule. A test fixture can construct invalid rows directly, so these tests do not depend on a large training dataset.
def test_invalid_label_is_reported():
df = pd.DataFrame({
"age": pd.Series([35], dtype="int64"),
"income": pd.Series([50_000.0], dtype="float64"),
"label": pd.Series([2], dtype="int64"),
})
errors = validate_training_data(df)
assert "label contains values other than 0 and 1" in errorsRun the tests with:
pytest tests/data -qA failed validation should block training. Otherwise, the pipeline may silently create a new model from data that violates the assumptions used to evaluate it.
Practical decisions
Use a small committed sample for fast CI checks, and validate the full training input in the training job. Keep the rules close to the code that consumes the data. When the schema changes intentionally, update the contract, sample data, and tests in the same pull request.
Also distinguish missing values from invalid values. A missing income may be allowed up to a limit, while a negative income may violate a separate range rule. Both checks should have explicit messages.
Exercise
Why should a validator return a list of errors instead of raising on the first invalid column?
Show answer
It lets one CI run show every discovered problem, making the data change faster to diagnose.