跳到正文

第 4 课 · Experiment Tracking

Log Parameters and Metrics

Log parameters and metrics in MLflow one at a time or in batches, record training curves with steps, and avoid common naming and logging mistakes.

Parameters and metrics are the heart of tracking. They answer two questions about every run: what did I choose? and what did I get? This lesson shows how to log both well.

Parameters: your choices

A parameter is a setting that you decide before a run. Examples are a learning rate, a tree depth, a model family or a random seed. You can log one or many:

Python
import mlflow

with mlflow.start_run():
    mlflow.log_param("model", "random_forest")
    mlflow.log_params({"n_estimators": 200, "max_depth": 6, "seed": 42})

Treat a parameter as fixed for the run. If a value changes during training, it is not a parameter; log it as a metric.

Log what you need to repeat the run: the seed, the data version, the feature list and preprocessing choices. A good test is to ask whether a colleague could recreate your result from the run page and the code.

Metrics: your results

A metric is a number that measures something. Log one value or a dictionary:

Python
with mlflow.start_run():
    mlflow.log_metric("accuracy", 0.91)
    mlflow.log_metrics({"precision": 0.88, "recall": 0.83})

Metrics are numbers. For words such as "good", use a tag instead.

Steps and training curves

You can record the same metric many times, each with a step, such as the epoch number. The UI can then draw a curve.

Python
with mlflow.start_run():
    for epoch in range(10):
        train_loss, val_loss = train_one_epoch()   # your function
        mlflow.log_metrics(
            {"train_loss": train_loss, "val_loss": val_loss}, step=epoch
        )

Pass step inside loops. It gives each point a clear position on the x-axis. The step is an integer, and gaps are allowed.

The stand-in below keeps a metric history and finds the best epoch. The loss numbers come from a formula, not from training a model.

Python Stand-in: metric history with steps

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.

The best value is not the last value. Summaries often show the latest value of a metric. If you care about the best epoch, log it separately, for example as best_val_loss.

Naming that helps later

  • Use consistent names: always val_accuracy, never sometimes acc_val.
  • Put the data split in the name: train_f1, val_f1, test_f1.
  • Include units when they matter: latency_ms.
  • Slashes can group related names, such as eval/accuracy.

A small helper keeps names consistent:

Python Stand-in: check metric names before logging

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.

This convention is our own. MLflow does not require it, but a team convention saves hours.

Overwriting and volume

A parameter is meant to be written once. If you try to log a different value for an existing parameter in the same run, MLflow raises an error. To try another value, start another run. Metrics are different, since each new log adds to the history.

If you log every batch of a long job, the history can grow very large. Logging every few hundred batches usually gives a curve that is just as useful.

Common mistakes

  • Checking the test score after every tuning decision. Then you tune to the test set and its score stops being an honest estimate. Tune on validation data and use the test set at the end.
  • Logging secrets as parameters, such as passwords or API keys. Anyone who can read the experiment can read them.
  • Using different names for the same measure in different scripts, which makes comparison hard.

Batch logging for real projects

In real training code, settings usually live in one dictionary. Log the whole dictionary, so you do not forget a setting when you add one:

Python
config = {
    "model": "random_forest",
    "n_estimators": 200,
    "max_depth": 6,
    "seed": 42,
    "data_version": "7",
}

with mlflow.start_run():
    mlflow.log_params(config)
    model = build_model(config)     # your function

The best pattern is to build the model from the same dictionary that you log. Then the record cannot drift away from the code. If you log values that you typed by hand, a later edit to the code may leave the log wrong, and a wrong log is worse than none.

Check the dictionary for secrets before you log it. Configuration files often contain connection strings.

Choosing which metrics to keep

More metrics are not always better. A useful starter set for classification is:

Metric Why keep it
Primary metric on validation data Used to choose models
The same metric on training data Shows overfitting when far apart
Precision and recall Explain the type of errors
Latency or model size Shows the practical cost

A large gap between training and validation scores suggests that the model memorizes the training data. Logging both makes that visible at a glance.

Reading the history

To retrieve every step of a metric, use the client:

Python
from mlflow import MlflowClient

history = MlflowClient().get_metric_history(run_id, "val_loss")
for point in history:
    print(point.step, point.value)

You can then compute your own summary, such as the best step, the average of the last five points or how fast the loss falls.

Units and scale

Write down units. A latency of 0.2 could be seconds or milliseconds. Also decide on a scale for percentages: either 0.91 or 91, never both in the same project. If two scripts disagree, sorting by that metric gives nonsense, and nobody gets an error message.

A quick review habit

After the first run of any new script, open it and read the logged values. Look for missing settings, odd names, wrong units and values that should not be there. Fixing the logging code now takes a minute. Discovering after a hundred runs that the seed was never recorded means that you cannot repair the history, so check early and check often. It is also a good moment to confirm that each metric name says which data split it came from.

Check your understanding

Quick check · 3 questions

of 3 answered You scored / 3 · perfect!

  1. 1. You want to chart validation loss over epochs. What should you pass?

    Logging the same metric with different steps creates a history that can be drawn.
  2. 2. Which value is a parameter rather than a metric?

    The depth is a choice you made before training. The others are measured results.
  3. 3. Why log the best validation loss separately?

    The last epoch can be worse than an earlier one.

Summary

  • Parameters are fixed choices; metrics are measured numbers.
  • Pass step to record curves over time.
  • Use consistent names with the data split in them.
  • Keep secrets out of tracking and keep the test set clean.

Next: Artifacts, Tags and Datasets

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