跳到正文

第 14 课 · Parameters, Metrics and Plots

DVC Metrics: Record and Compare Results

Save model and data quality numbers in metrics files, register them in dvc.yaml, compare versions with dvc metrics show and diff, and avoid misleading scores.

Parameters describe what you tried. Metrics describe what happened. A metric can be model accuracy, an error value, a row count after cleaning, or training time. DVC reads metrics files and compares them across versions.

Write a metrics file

A metrics file is a small structured file, usually JSON or YAML, with numbers in it. Your script writes it.

Python
# Read-only: the end of an evaluation script
import json

metrics = {"accuracy": 0.874, "f1": 0.861, "test_rows": 2000}
with open("reports/metrics.json", "w") as f:
    json.dump(metrics, f, indent=2)

Nested objects are fine and appear as nested names, such as per_class.positive.f1.

Register it in dvc.yaml

Declare it so DVC knows it is a metric. The top-level metrics list in dvc.yaml points at files:

YAML
metrics:
  - reports/metrics.json

stages:
  evaluate:
    cmd: python src/evaluate.py
    deps:
      - src/evaluate.py
      - models/model.pkl
      - data/split/test.csv
    outs:
      - reports/metrics.json:
          cache: false

cache: false means DVC does not store the file in its cache; you commit it with Git, so the values appear in code review. This is usually right for small files. You may also meet a metrics: field inside a stage in existing projects; the -m and -M flags of dvc stage add create metrics entries from the command line.

Show and compare

Terminal
# Read-only: view and compare
dvc metrics show
dvc metrics diff                    # workspace versus last commit
dvc metrics diff main my-branch
dvc metrics diff --all --md         # include unchanged values, as Markdown

dvc metrics diff shows only changed metrics unless you add --all. Useful flags:

Flag Effect
--targets Compare specific files, even ones not declared
--precision <n> Round decimals to n digits
--json Machine-readable output
--md Markdown table, handy for pull request comments
--no-path Hide the path column

Choose metrics honestly

DVC compares numbers. It cannot tell you whether they mean anything.

  • Match the metric to the goal. Accuracy can look great on unbalanced data while the rare class fails completely. Add precision, recall or F1 per class.
  • Keep the test set fixed while comparing. If the test data changes, score differences may not reflect the model. Because your test split is tracked, you can see when it changed.
  • Do not tune on the test set. Use a validation set for choosing settings.
  • Report variation. One run with one seed can be lucky. Several seeds show the spread.
  • Record data counts so a silent loss of rows becomes visible.

Try the idea

This stand-in compares two metrics dictionaries and applies a simple quality gate, the way a script in CI might. It is not DVC's output format.

Python Stand-in: compare metrics with a quality gate

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Overall accuracy rose a little, yet the negative class got much worse. A single headline number would hide that.

Metrics for data work too

Metrics are not only for models. A cleaning stage can report how many rows it removed, the share of missing values, or the number of duplicates. If a new data version removes 40% of rows, you notice in the diff.

Common mistake: writing metrics by hand or copying numbers from a notebook. The file should come from the pipeline, so that it matches the data, code and parameters recorded in dvc.lock.

Keep reviews readable

Keep metrics files short. Round values to a sensible number of digits in your script, or use --precision in comparisons. Put detailed per-example results in a separate output that is cached by DVC, not in the metrics file.

Make metrics trustworthy

A metric is only useful when everyone agrees what it means. Write down the definition next to the code, for example: "accuracy is the share of test rows where the predicted label equals the true label". Specify which data it is computed on, how ties or missing values are handled, and how averages are taken for several classes.

Also protect against a few quiet mistakes:

  • Leakage: information from the test set sneaks into training, for example by computing a vocabulary or an average on all rows before splitting. Scores then look better than reality.
  • Tiny test sets: with 50 examples, one extra correct answer moves accuracy by two percentage points, so small differences mean little.
  • Changed definitions: if you change how a metric is computed, older values are no longer comparable. Rename the metric or note the change.

A review routine

When a pull request changes metrics, ask: did the data change, did the parameters change, or did the code change? Check dvc diff, dvc params diff and the Git diff. If none explains the movement, suspect randomness or an environment change, and rerun with the same seed. Keep a note of what you found, because the next reviewer will ask the same question.

A small, stable set

Resist the urge to track dozens of numbers. A long table hides the few that matter. Choose one primary metric that reflects the goal, a few guard metrics that must not get worse (for example F1 for the smallest class), and a couple of data counts. Write down which is which.

When a guard metric moves the wrong way, stop and investigate even if the primary metric improved. And when the goal changes, update the list in its own commit, with a note, so later readers understand why the columns changed.

Finally, keep the names stable. If you rename a metric key, older versions will no longer line up with newer ones in comparisons.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. Why mark a small metrics file with cache: false?

    Small text files work well in Git, where their changes are visible.
  2. 2. What does dvc metrics diff show without --all?

    Unchanged values are hidden unless you ask for all.
  3. 3. Accuracy rose but a minority class F1 fell sharply. What should you conclude?

    Different metrics capture different failures, especially on unbalanced data.
  4. 4. Why watch the test set while comparing scores?

    Comparisons are fair only when the evaluation data stays the same.

Summary

  • Scripts write small JSON or YAML metrics files that you declare in dvc.yaml.
  • dvc metrics show and diff compare values across versions.
  • Commit small metrics files with Git using cache: false.
  • Pick metrics that match your goal and watch for hidden regressions.
  • Compare only on the same evaluation data.

Next: DVC Plots

你的学习进度保存在此浏览器中,无需账号。