Sub topic 4
Logging parameters, metrics and tags
This chapter assumes you can run a Databricks notebook, write basic Python with context managers, and train a scikit-learn model. It also assumes you know what an experiment and a run are from the previous chapters. Here you will learn the three most common things a run records, and how to avoid the usual mistakes.
Three kinds of logged values
A run stores different kinds of information, and each kind has its own call.
| Kind | Call | Typical value | Can change after logging? |
|---|---|---|---|
| Parameter | `mlflow.log_param(key, value)` | Learning rate, `C`, number of trees | No. A key can be logged once per run. |
| Metric | `mlflow.log_metric(key, value, step=None)` | Accuracy, loss, RMSE | Yes. Each call adds a new value. |
| Tag | `mlflow.set_tag(key, value)` | Stage, owner, dataset version | Yes. Setting a tag again overwrites it. |
A parameter is an input to the run, such as a setting you chose before training. A metric is a numeric result you measure. A tag is a free-form label used to organize and filter runs.
A first logged run
The example below sets an experiment by absolute workspace path, then records one value of each kind.
import mlflow
mlflow.set_experiment("/Users/<your-email>/iris-tracking")
with mlflow.start_run(run_name="baseline") as run:
mlflow.log_param("C", 1.0)
mlflow.log_metric("accuracy", 0.93)
mlflow.set_tag("stage", "exploration")
print(run.info.run_id)Replace <your-email> with your own workspace user name. The with block ends the run automatically, even if an error occurs. Without it, you must call mlflow.end_run() yourself, or the next start_run call raises an error because a run is still active.
The printed run ID identifies this run. You will use it later to find the run, load its artifacts, or register its model.
Metrics over time
A metric can be logged many times under the same key. Use the step argument to say where each value belongs on the x-axis, for example an epoch or an iteration.
import mlflow
with mlflow.start_run(run_name="loss-curve"):
for epoch, loss in enumerate([0.9, 0.6, 0.45, 0.4]):
mlflow.log_metric("train_loss", loss, step=epoch)The experiment UI draws these values as a line chart. If you omit step, MLflow uses 0 for every call. The values are all kept, but the chart cannot order them in a useful way.
When you have several values at once, mlflow.log_params(dict) and mlflow.log_metrics(dict) log them in a single call. This is shorter, and it sends fewer requests to the tracking server.
Common errors
- Changing a parameter. Logging
Cas 1.0 and later as 10.0 in the same run raises anMlflowException. Parameters are immutable within a run. If a value changes, it is probably a metric, or you need a second run. - Logging a non-number as a metric. Metrics must be numeric. Put text such as
"cleaned_v2"in a tag or a parameter. - Forgetting that parameters are stored as strings.
1.0becomes"1.0". Filters on parameters therefore compare strings, not numbers, so cast values when you query them. - Logging outside a run. In a Databricks notebook,
mlflow.log_paramwith no active run starts one for you in the notebook experiment. This is convenient, but it can leave a run open that you did not mean to create. Prefer an explicitwith mlflow.start_run()block. - Reusing metric names with different meanings. If one run logs
accuracyon training data and another logs it on test data, comparisons mislead you. Use distinct names such astrain_accuracyandtest_accuracy.
Choosing between a parameter, a metric and a tag
Ask what the value is for.
- If it is a setting you chose and want to compare across runs, log a parameter.
- If it is a number the run produced, log a metric.
- If it describes or groups the run and is not a result, log a tag.
A number can be a parameter or a metric depending on its role. The number of training rows is a parameter if you chose it, as in n_samples=1000. It is a tag or a parameter if it only describes the dataset. A validation score is always a metric.
Exercises
Exercise
Inside one run, you call mlflow.log_param("max_depth", 5) and later mlflow.log_param("max_depth", 8). What happens, and what should you do instead if the depth really differs between two experiments?
Show answer
The second call raises an MlflowException, because a parameter key can be logged only once per run and cannot be overwritten. If the depth differs between experiments, start a separate run for each depth, and log max_depth once in each.
Exercise
You train a network for 20 epochs. How do you log the validation loss so the UI shows it as a curve?
Show answer
Call mlflow.log_metric("val_loss", value, step=epoch) once per epoch, so that every value is stored with its step number.