Sub topic 11
Validating data before training
This chapter assumes you know the train, validate, test, deploy workflow, can read basic pandas and NumPy, and have seen the retraining triggers from earlier chapters. A trigger has fired and the pipeline has pulled a fresh training set. This chapter covers the next step, which is deciding whether that data is fit to train on.
Why validation comes before training
An automated pipeline trains whatever it receives. A person retraining by hand would notice that a column is empty. A scheduled job will not notice, and it will train a model on the broken data and may promote it.
Typical causes of bad training data are:
- An upstream team renames a column or changes a unit, for example dollars to cents.
- A join silently drops rows, so the table is half its usual size.
- A logging bug fills a feature with nulls or a constant.
- A label pipeline stops, and recent rows carry default labels.
- Someone injects malicious records (data poisoning).
Validation answers "is this data broken?" Drift detection answers "has the world changed?" These are different questions. Drift is the reason to retrain, so a drifted feature must not fail validation. A feature that is 100% null must.
What to check
| Check | Example rule | Typical severity |
|---|---|---|
| Schema | Required columns exist with expected dtypes | Hard |
| Volume | Row count is at least the minimum | Hard |
| Completeness | Null rate per column is below a limit | Hard or soft |
| Domain and range | Age is between 0 and 120; country is in a known set | Hard |
| Uniqueness | Duplicate rows are under 1% | Soft |
| Label sanity | Positive rate is near the reference rate | Hard |
| Freshness | Newest record is no older than expected | Soft |
| Distribution | No feature moved far beyond normal drift | Soft, escalate if extreme |
A hard failure stops the run. A soft failure is logged and reported but does not stop it. Choosing the severity is a design decision, and you should write it down.
A minimal validator
The function below checks a pandas DataFrame and returns a list of (severity, check, detail) tuples. Returning data instead of raising on the first problem lets you save a full report.
import pandas as pd
SCHEMA = {"age": "float64", "country": "object",
"amount": "float64", "label": "int64"}
def validate(df, schema, ref_label_rate, min_rows=1000,
max_null_rate=0.05, label_tol=0.10):
failures = []
if len(df) < min_rows:
failures.append(("hard", "row_count", f"{len(df)} < {min_rows}"))
missing = sorted(set(schema) - set(df.columns))
if missing:
failures.append(("hard", "missing_columns", str(missing)))
return failures
for col, dtype in schema.items():
if str(df[col].dtype) != dtype:
failures.append(("hard", "dtype",
f"{col}: {df[col].dtype} != {dtype}"))
rate = df[col].isna().mean()
if rate > max_null_rate:
failures.append(("hard", "null_rate", f"{col}: {rate:.2f}"))
bad_age = ((df["age"] < 0) | (df["age"] > 120)).mean()
if bad_age > 0:
failures.append(("hard", "age_range", f"{bad_age:.2f} out of range"))
dup_rate = df.duplicated().mean()
if dup_rate > 0.01:
failures.append(("soft", "duplicates", f"{dup_rate:.2f}"))
label_rate = df["label"].mean()
if abs(label_rate - ref_label_rate) > label_tol:
failures.append(("hard", "label_rate", f"{label_rate:.2f}"))
return failures
df = pd.DataFrame({
"age": [34.0, 41.0, -5.0, 29.0],
"country": ["DE", "US", "US", None],
"amount": [10.0, 25.5, 7.2, 13.1],
"label": [0, 1, 0, 0],
}).astype({"label": "int64"})
failures = validate(df, SCHEMA, ref_label_rate=0.2, min_rows=3)
for f in failures:
print(f)
blocking = [f for f in failures if f[0] == "hard"]
print("halt" if blocking else "continue")This run prints two hard failures (null_rate on country and age_range) and then halt.
Where the reference values come from
Rules like "label rate near 0.2" need a reference. Compute reference statistics from the last training set that produced an accepted model, and store them with that model's version. Do not hard-code them, because they would go stale. Do not use the previous raw extract either, because a bad extract would then become the reference.
Many teams use a library such as Great Expectations, TensorFlow Data Validation, or Pandera instead of hand-written checks. They give you declarative rules, schema inference, and readable reports. The principles in this chapter apply to any of them.
Edge cases
- Immature labels. With delayed labels, the newest rows may have a default label of 0 because the outcome has not happened yet. A label-rate check catches this. A better fix is to exclude rows younger than the label delay when you build the dataset.
- Training/serving skew. Validate the features as the model will see them in production, not only the raw tables. If training computes
amountin dollars and serving uses cents, each side looks fine alone. - Leakage. A column that is almost perfectly correlated with the label, and that appeared recently, usually means a field is filled in after the outcome. Add a soft check on single-feature predictive power.
- Over-strict rules. If checks fail every week on harmless variation, people learn to override them. Start with loose limits taken from a few historical good runs, and tighten them only when you have evidence.
- Slow poisoning. Per-run checks pass when bad data arrives gradually. Compare against a fixed long-term reference as well as the previous run.
- Checks that cannot fail. A rule that was never tested may be passing because of a bug. Feed each check a known-bad sample in a unit test.
What the stage produces
Validation should output a report that records the dataset identifier, the rule set version, each failure with its severity, and the final decision. Store it next to the training run. When a model misbehaves later, the report shows what you checked and what the data looked like. It also feeds the lineage records covered in the next chapter.
Alert the data owner when a run halts, and include the failing check names. A halt with no alert means the model silently stops updating, which is a failure you only notice weeks later. Track the halt count as a pipeline metric.
Exercise
A drift trigger fires because the PSI of the feature amount is 0.35. Your validator also compares amount against reference statistics. Should a large shift in amount fail validation as a hard failure? Explain, and name one validation result that should block training.
Show answer
No. Drift is the reason the pipeline was triggered, so a moderate or large shift is expected and the new model should learn it. Making it a hard failure would stop the pipeline from fixing the problem it was started to fix. Only an implausible shift, such as values that are all null, constant, or in the wrong unit, should block. A hard failure that should block training is a null rate above the limit on a feature, a label rate far from the reference, or a missing required column.