Sub topic 10
Pipelines: Tying Code, Parameters, and Data Together
Assume you know basic Python, the command line, Git, and how to train a model. A machine learning pipeline is a sequence of named steps that transforms inputs into outputs. Each step declares what it reads, what it runs, and what it creates.
A pipeline makes dependencies visible. If the training code changes, the training stage should run again. If only a report changes, data preparation and training do not need to run again.
Model the work as stages
A typical project separates preparation, training, and evaluation:
| Stage | Inputs | Command | Output |
|---|---|---|---|
| prepare | Raw data and preparation code | `python -m my_project.data.prepare` | Processed data |
| train | Processed data, training code, and parameters | `python -m my_project.train` | Model |
| evaluate | Model and test data | `python -m my_project.evaluate` | Metrics |
Each stage should have one clear responsibility. It should read inputs from known locations and write outputs to known locations. Avoid hidden inputs such as a file in your home directory or a value edited manually in a notebook.
The relationship looks like this:
Declare dependencies and outputs
Tools such as DVC can store the pipeline definition in dvc.yaml. The following file declares two stages:
stages:
prepare:
cmd: python -m my_project.data.prepare
deps:
- src/my_project/data/prepare.py
- data/raw
outs:
- data/processed
train:
cmd: python -m my_project.train --config configs/train.yaml
deps:
- src/my_project/train.py
- data/processed
params:
- configs/train.yaml:
- learning_rate
- batch_size
outs:
- models/model.pklThe cmd field is the command to run. A deps entry is an input whose change can invalidate the stage. A params entry identifies configuration values that affect the result. An outs entry identifies files or directories produced by the command.
After defining the stages, run:
dvc reproDVC calculates which stages are out of date. It reruns a stage when its code, data, or tracked parameters changed. It can also reuse a cached output when the inputs match a previous run.
Avoid common pipeline errors
A pipeline can appear reproducible while still missing important dependencies.
- Declare every file that affects a result, including lookup tables and feature definitions.
- Write outputs to declared paths instead of changing files in place.
- Do not use the current time as an undeclared input.
- Keep random seeds in configuration when randomness affects the output.
- Make stage commands runnable from the repository root.
- Check that an output is complete before a later stage reads it.
Exercise
Exercise
The learning rate changes, but the pipeline does not rerun training. What should you inspect first?
Show answer
Check that the configuration file and the learning-rate key are listed under the training stage's params, and confirm that the command uses that configuration file.