Sub topic 4
Managing data: collection, validation and versioning
This chapter assumes you can train and evaluate a supervised model in Python, use Git from the command line, and read a pandas DataFrame. It covers the data stage of the lifecycle. It covers where data comes from, how to check it before training, and how to version it so a result can be traced to the exact rows that produced it.
Why data needs its own discipline
In ordinary software, behavior comes from code, and Git versions the code. In a machine learning system, behavior comes from code and data together. Change a single column in the training table and the model changes, even if no line of code did.
Three problems follow from this:
- Data changes quietly. A source system renames a field, a vendor changes a unit, or a pipeline starts emitting nulls. Nothing crashes. The model trains and gets worse.
- Data is large. Git handles source files well but not multi-gigabyte tables.
- Data is mutable. A file at
data/train.csvmay be overwritten tomorrow, and then last week's result can no longer be reproduced.
The data stage therefore has three jobs: collect data on purpose, validate it automatically, and version it so each run points at an exact snapshot.
Collecting data
Collection decisions are made once but affect every later stage. Record these facts for each source:
- Origin. Which system, table, API or file produced it, and who owns it.
- Collection period. The dates covered. Training on a window that misses a seasonal pattern gives a model that fails in that season.
- Label source. How the target was produced: human annotation, a business event such as "customer cancelled", or a downstream system. Labels often arrive late, which affects how fast you can evaluate and retrain.
- Sampling. Whether the data is all events or a sample, and how it was sampled. A biased sample produces a biased model.
- Permissions. Whether you may use the data for this purpose. Personal data needs a documented legal basis and often needs to be removed or masked.
A common error is leakage. Leakage means a feature contains information that will not be available at prediction time, such as a "refund issued" flag used to predict fraud. Leaky data gives excellent offline scores and poor production results. Check each feature against the question: "Will I know this at the moment I need to predict?"
Validating data
Validation means writing down what good data looks like and checking it automatically on every new batch. Treat these checks like unit tests for data. They run in the pipeline, and a failure stops the run.
Typical checks fall into four groups:
| Check type | Example | Catches |
|---|---|---|
| Schema | Column `age` exists and is an integer | Renamed or retyped fields |
| Range and domain | `age` between 0 and 120; `country` in a known list | Unit changes, corrupt values |
| Completeness | Null rate of `income` below 2% | Broken upstream joins |
| Distribution | Mean and spread of a feature near the training values | Silent shifts in the source |
The following example uses plain pandas, so it runs without extra tools. Dedicated libraries such as Great Expectations, Pandera or TensorFlow Data Validation offer the same idea with more features and reporting.
import pandas as pd
EXPECTED_COLUMNS = {"age": "int64", "income": "float64", "country": "object"}
VALID_COUNTRIES = {"DE", "FR", "US"}
def validate(df: pd.DataFrame) -> list[str]:
"""Return a list of problems. An empty list means the batch passed."""
problems = []
for column, dtype in EXPECTED_COLUMNS.items():
if column not in df.columns:
problems.append(f"missing column: {column}")
elif str(df[column].dtype) != dtype:
problems.append(f"{column} has dtype {df[column].dtype}, expected {dtype}")
if problems:
return problems # later checks assume the columns exist
if not df["age"].between(0, 120).all():
problems.append("age outside 0-120")
if df["income"].isna().mean() > 0.02:
problems.append("income null rate above 2%")
unknown = set(df["country"].dropna()) - VALID_COUNTRIES
if unknown:
problems.append(f"unknown countries: {sorted(unknown)}")
return problems
good = pd.DataFrame(
{"age": [34, 51], "income": [52000.0, 61000.0], "country": ["DE", "US"]}
)
bad = pd.DataFrame(
{"age": [34, 250], "income": [52000.0, None], "country": ["DE", "XX"]}
)
print(validate(good)) # []
print(validate(bad))Running it prints an empty list for the good batch. For the bad batch it reports the age range, the income null rate and the unknown country.
Choosing thresholds
Thresholds are a trade-off. Strict checks catch more real problems but also block runs for harmless variation. Loose checks let bad data through. Start with rules you can justify from the business meaning of a field, such as an age range. Set statistical limits, such as a null rate, from historical batches, and revisit them when a legitimate change happens.
What to do on failure
Decide the policy before the first failure, not during it:
- Block. Stop the pipeline and keep the previous model. Use this for schema errors and for any check that makes training meaningless.
- Quarantine. Move the failing batch to a separate location for inspection and continue with the last good data.
- Warn. Log the issue and continue. Use this only for checks that are advisory.
Whatever the policy, a failure must produce an alert that reaches a person who owns the source.
Versioning data
Versioning means that every training run can name the exact data it used, and that data can be retrieved later. There are three common approaches.
| Approach | How it works | Strengths | Limits |
|---|---|---|---|
| Immutable, dated paths | Write each snapshot to a new path such as `s3://bucket/train/2026-11-30/` and never overwrite | Simple, needs no extra tool | Relies on discipline; no link to Git commits |
| Data version control tools (DVC, lakeFS) | Store large files outside Git and commit small pointer files or branch metadata | Data versions line up with code commits; supports branching | Extra tool to learn and operate |
| Table formats with time travel (Delta Lake, Iceberg) | The table keeps a history, and you query it as of a version or timestamp | Good for tables already in a lakehouse | Tied to that storage platform |
With DVC, the workflow looks like this:
dvc init
dvc add data/train.csv # creates data/train.csv.dvc, a small pointer file
git add data/train.csv.dvc data/.gitignore
git commit -m "Add training snapshot"
dvc push # uploads the data to remote storageThe .dvc file contains a content hash. When someone checks out an older Git commit and runs dvc checkout, they get the matching data. This is what ties a data version to a code version.
Whichever approach you use, record a dataset identifier with each training run. A content hash, a snapshot path or a table version all work. If your experiment tracker has a place for it, log it as a parameter next to the hyperparameters, as in this fragment:
import hashlib
import mlflow
def file_hash(path: str) -> str:
digest = hashlib.sha256()
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(1 << 20), b""):
digest.update(chunk)
return digest.hexdigest()[:12]
with mlflow.start_run():
mlflow.log_param("train_data_hash", file_hash("data/train.csv"))The later chapter on experiment tracking builds on this. For now, the point is that the identifier makes a result traceable to its data.
Common errors
- Overwriting the training file. The most common cause of irreproducible results. Write snapshots to new paths.
- Validating only at training time. The same checks should also run on data arriving at serving time, or a broken feed goes unnoticed until accuracy drops.
- Splitting after leakage. Computing statistics, such as a scaler's mean, on the full dataset before splitting lets test information leak into training. Split first, then fit transformations on the training part only.
- Random splits on time-ordered data. If rows are events over time, a random split lets the model train on the future. Split by time.
- Versioning data but not labels. Labels change as annotators correct mistakes. Version them with the features.
- Treating the validation schema as fixed. Legitimate changes happen. Update the checks through a reviewed change, like code.
Putting it together
A sound data stage in a pipeline runs in this order: ingest a batch, run validation, stop or quarantine on failure, write an immutable snapshot on success, record its identifier, and start training from that identifier. Each step is small. Together they make the later stages, such as tracking, evaluation and retraining, trustworthy because they rest on known data.
Exercise
A team's model accuracy dropped after a nightly retraining job. No code changed. The training file data/train.csv is overwritten each night, and no validation runs. Name two changes that would help them find the cause and prevent a repeat.
Show answer
First, write each nightly extract to a new immutable path (or version it with a tool such as DVC) and log its identifier with every training run, so the run that dropped can be compared with the previous one. Second, add automated validation (schema, range, null-rate and distribution checks) before training, with a block or quarantine policy and an alert, so a bad upstream change stops the job instead of producing a worse model.
Exercise
Why should you split data into train and test sets before fitting a scaler, and how does this relate to data management?
Show answer
Fitting the scaler on the full dataset uses test-set statistics when preparing the training data, which leaks information and inflates test scores. Splitting first and fitting transformations on the training part only keeps the test set a fair stand-in for unseen data. It belongs to data management because the split and its snapshot are part of the versioned dataset definition.