Sub topic 8
Tracking parameters and metrics
This chapter assumes you can define a stage in dvc.yaml and run dvc repro, as in the previous chapter. It also assumes you can read a short Python training script. The goal here is to make each run answer two questions: which settings produced this model, and how good was it?
Why parameters and metrics get their own tracking
A pipeline stage already tracks its command, input files, and output files. Two other kinds of information decide whether a run is reproducible and comparable:
- Parameters are the settings you choose before training, such as the number of trees or the learning rate. They are inputs, but they are values, not files.
- Metrics are numbers the run produces, such as accuracy or loss. They are outputs, but you want to read and compare them, not store them as large binary data.
If you hard-code parameters in a script, a change to one of them is just a code change. DVC cannot tell that only one setting changed, so the stage reruns for any edit to the script. If you print metrics to the console, nobody can compare them across Git commits later.
DVC solves both with plain text files that Git versions normally:
- Parameters live in
params.yaml. A stage lists the keys it reads, and DVC reruns the stage only when those values change. - Metrics live in a small file such as
metrics.json. The stage declares it as a metrics output, and DVC can show it and diff it between Git revisions.
Defining parameters
By default DVC looks for a file called params.yaml in the project root. It holds nested YAML:
train:
n_estimators: 100
max_depth: 5
seed: 42A stage declares which keys it depends on with the params field in dvc.yaml. Nested keys use dot notation:
stages:
train:
cmd: python src/train.py data/prepared models/model.pkl
deps:
- src/train.py
- data/prepared
params:
- train.n_estimators
- train.max_depth
- train.seed
outs:
- models/model.pkl
metrics:
- metrics.json:
cache: falseThree details matter:
- DVC compares values, not the whole file. If you edit
train.seedbut the stage lists onlytrain.n_estimatorsandtrain.max_depth, the stage stays valid. - Editing an unrelated key, a comment, or the formatting of
params.yamldoes not invalidate a stage that does not list the changed key. - The values read at each run are written into
dvc.lock, next to the input and output hashes. That is what lets you recover the exact settings of an old run from Git history.
You can also create the same stage from the command line. -p adds parameter dependencies and -M adds a metrics file that Git tracks directly:
dvc stage add -n train \
-d src/train.py -d data/prepared \
-p train.n_estimators,train.max_depth,train.seed \
-o models/model.pkl \
-M metrics.json \
python src/train.py data/prepared models/model.pklA training script that reads parameters and writes metrics
DVC does not inject parameters into your code. The script must read params.yaml itself and write the metrics file. The script below assumes the earlier prepare stage wrote train.csv and test.csv into data/prepared, each with a numeric label column.
import json
import pickle
import sys
from pathlib import Path
import pandas as pd
import yaml
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, f1_score
prepared_dir = Path(sys.argv[1])
model_path = Path(sys.argv[2])
with open("params.yaml") as f:
params = yaml.safe_load(f)["train"]
train = pd.read_csv(prepared_dir / "train.csv")
test = pd.read_csv(prepared_dir / "test.csv")
X_train, y_train = train.drop(columns=["label"]), train["label"]
X_test, y_test = test.drop(columns=["label"]), test["label"]
model = RandomForestClassifier(
n_estimators=params["n_estimators"],
max_depth=params["max_depth"],
random_state=params["seed"],
)
model.fit(X_train, y_train)
predictions = model.predict(X_test)
metrics = {
"accuracy": round(accuracy_score(y_test, predictions), 4),
"f1": round(f1_score(y_test, predictions, average="weighted"), 4),
}
model_path.parent.mkdir(parents=True, exist_ok=True)
with open(model_path, "wb") as f:
pickle.dump(model, f)
with open("metrics.json", "w") as f:
json.dump(metrics, f, indent=2)Reading every value from params.yaml, including the random seed, is what makes the dependency honest. If the script also reads a value that the stage does not list, DVC will not rerun the stage when that value changes. This is the most common cause of a stale model.
Declaring and reading metrics
A metrics file is a small JSON, YAML, or TOML file with numeric values. Declaring it under metrics in dvc.yaml marks it as a metrics output, which enables the comparison commands.
The cache: false option tells DVC not to move the file into its cache. The file then stays in the workspace and Git versions it directly. This is the right choice for a file of a few bytes, because it lets you read old values with git show or any Git viewer, with no DVC cache involved. Without cache: false, DVC treats the file like any output and replaces it with a pointer in Git's view.
After dvc repro, read the current values:
dvc repro
dvc metrics showPath accuracy f1
metrics.json 0.9123 0.9101Commit the results so the run is recorded:
git add dvc.yaml dvc.lock params.yaml metrics.json
git commit -m "Train baseline model"Comparing across revisions
Once two commits hold different results, DVC compares them without you checking anything out. Both commands accept Git revisions: commit hashes, branches, and tags.
dvc params diff
dvc metrics diff
dvc metrics diff v1.0 HEADWith no arguments, the commands compare your workspace against HEAD. This is useful right after you edit params.yaml and rerun the pipeline, before you commit.
Example output after raising n_estimators from 100 to 200:
Path Param HEAD workspace
params.yaml train.n_estimators 100 200Path Metric HEAD workspace Change
metrics.json accuracy 0.9123 0.9187 0.0064
metrics.json f1 0.9101 0.9172 0.0071| Command | Compares | Reads from |
|---|---|---|
| `dvc params diff` | Parameter values | `params.yaml` and the values recorded in `dvc.lock` |
| `dvc metrics show` | Nothing, shows current values | Metrics files in the workspace |
| `dvc metrics diff` | Metric values and their change | Metrics files at two revisions |
Two options are worth knowing. --targets limits the output to specific files, which helps when a project has several metrics files. --json and --md change the output format, and --md is useful for pasting a table into a pull request.
How invalidation works internally
When you run dvc repro, DVC checks each stage in dependency order. A stage is skipped only if every recorded dependency matches dvc.lock: the command string, the hash of each file dependency, and the value of each listed parameter. Any mismatch means the stage reruns, and downstream stages rerun if its outputs changed.
This gives you two practical consequences:
- Changing
train.max_depthretrains the model but does not rerunprepare, becausepreparedoes not depend on that key. - Changing a value that no stage lists does nothing, which is why listing keys precisely matters.
Common errors
- A key listed in
dvc.yamlis missing fromparams.yaml. DVC reports an error about the missing parameter when it runs or checks the stage. Check spelling and nesting.train.max_depthmeans the keymax_depthundertrain. - The script reads a key the stage does not list. The pipeline never reruns when that key changes. Compare the keys in your script with the
paramslist. metrics.jsonis not tracked by Git. If you forgetcache: false, DVC caches the file and adds it to.gitignore. Thengit add metrics.jsonfails anddvc metrics diffcannot read old values without the cache. Fix the stage and rerun it.- The metrics file holds non-numeric or deeply varied content. DVC can display nested values, but comparison works best with a flat set of numbers.
- You forgot to commit
dvc.lock. Without it,dvc params diffagainstHEADshows nothing useful, since the old values were never recorded. - A non-deterministic script. If you do not fix the seed, two runs with identical parameters give different metrics, and a diff shows noise as if it were improvement. Put the seed in
params.yaml, as in the example.
Exercises
Exercise
You change train.seed in params.yaml, but the train stage lists only train.n_estimators and train.max_depth under params. The training script does read train.seed. What happens when you run dvc repro, and how do you fix it?
Show answer
DVC reports that nothing changed and skips the stage, because it only tracks the listed keys. The saved model is now out of date with respect to the seed. Fix it by adding train.seed to the stage's params list in dvc.yaml, then run dvc repro again.
Exercise
You raised train.n_estimators from 100 to 200 and ran dvc repro, but have not committed. Which command shows both the parameter change and the metric change against the last commit, and why is cache: false on metrics.json needed for the metric comparison?
Show answer
Run dvc params diff and dvc metrics diff. With no arguments each compares the workspace to HEAD. The cache: false option keeps metrics.json as a normal text file that Git versions, so DVC can read its contents at HEAD directly from Git history.