Sub topic 11
Validating Data Before Training
Assume you know the basic machine learning workflow: data is used to train a model, validation data measures its quality, and a deployed model serves predictions. You should also be comfortable with Python, pandas, and basic version control.
A retraining job must reject bad input before it spends time and money training. Data validation checks whether the new dataset has the expected structure, values, and time boundaries. It should produce a clear validation result as an artifact, such as a report containing passed checks, failures, row counts, and the dataset version.
Checks to perform
| Check | Example rule | Why it matters |
|---|---|---|
| Schema | Required columns exist | Prevents missing-feature errors |
| Types | `amount` is numeric | Prevents invalid model input |
| Missing values | `user_id` is never missing | Avoids ambiguous records |
| Ranges | `age` is between 0 and 120 | Detects corrupt values |
| Duplicates | One row per transaction ID | Prevents duplicated training weight |
| Labels | Labels are present and valid | Ensures supervised training is possible |
| Time | Events occur before the training cutoff | Prevents future information leakage |
A schema check alone is insufficient. A file can have the correct columns while containing nulls, impossible values, duplicated records, or labels from the wrong time period.
A small validation function
The following example validates a transaction dataset before training. In a real pipeline, the cutoff date would come from the run configuration, and the result would be stored with the training artifacts.
from io import StringIO
import pandas as pd
def validate_training_data(df, training_cutoff):
errors = []
required = {"transaction_id", "amount", "age", "label", "event_time"}
missing_columns = required - set(df.columns)
if missing_columns:
errors.append(f"missing columns: {sorted(missing_columns)}")
if errors:
return errors
if not pd.api.types.is_numeric_dtype(df["amount"]):
errors.append("amount must be numeric")
if not pd.api.types.is_numeric_dtype(df["age"]):
errors.append("age must be numeric")
if df["transaction_id"].isna().any():
errors.append("transaction_id contains missing values")
if df["transaction_id"].duplicated().any():
errors.append("transaction_id contains duplicates")
if df["amount"].isna().any() or (df["amount"] < 0).any():
errors.append("amount contains missing or negative values")
if df["age"].isna().any() or (~df["age"].between(0, 120)).any():
errors.append("age contains missing or out-of-range values")
if not df["label"].isin([0, 1]).all():
errors.append("label must contain only 0 or 1")
event_time = pd.to_datetime(df["event_time"], errors="coerce", utc=True)
if event_time.isna().any():
errors.append("event_time contains invalid timestamps")
elif (event_time > training_cutoff).any():
errors.append("data contains events after the training cutoff")
return errors
csv = StringIO("""transaction_id,amount,age,label,event_time
t1,25.50,34,1,2026-11-01T12:00:00Z
t2,10.00,41,0,2026-11-02T12:00:00Z
""")
data = pd.read_csv(csv)
cutoff = pd.Timestamp("2026-11-30T00:00:00Z")
errors = validate_training_data(data, cutoff)
if errors:
raise ValueError("Data validation failed:\n- " + "\n- ".join(errors))
print(f"Validation passed for {len(data)} rows")Handling failures
A failed validation should stop the training run. Do not silently remove invalid rows unless that behavior is explicitly defined and measured. Silent filtering can hide an upstream data outage.
Store the validation report with the dataset identifier, code version, row counts, and checks performed. This creates a record of why a retraining run was accepted or rejected.
Exercise
Why should a retraining pipeline reject rows with event times after the training cutoff?
Show answer
Those rows may contain information from the future relative to the training decision. Including them can cause target leakage and make offline evaluation look better than real production performance.