Sub topic 4
Logging parameters, metrics and tags
This chapter covers the three kinds of small values you attach to a run. You should already know how to open a run with mlflow.start_run() and how an experiment groups runs. You should also have a notebook attached to compute and be able to train a scikit-learn model. The earlier chapters on experiments, runs and workspace experiments cover that setup.
The working model
A run holds three kinds of key-value records. They look similar, but MLflow treats each one differently.
| Kind | What it describes | Value type | Can it change? | Typical use |
|---|---|---|---|---|
| Parameter | An input to the run | String (other types are converted) | No, one value per key | Hyperparameters, data version, random seed |
| Metric | A measured result | Number | Yes, as a series of values over steps | Accuracy, loss, RMSE |
| Tag | A label about the run | String | Yes, you can overwrite it | Stage, owner, ticket number, dataset name |
Use parameters for what you chose, metrics for what you measured, and tags for what you want to remember or filter by.
Logging a first run
The following code sets an experiment and logs one parameter, one metric and one tag. Replace <your-email> with your Databricks user name. On Databricks, an experiment set by absolute path must live in a folder that exists.
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)The with block ends the run when the block exits, and it marks the run as failed if an exception escapes. Without it, you must call mlflow.end_run() yourself, or the run stays active and the next log_* call writes to the wrong run.
Each logging function has a batch form that sends one request instead of many:
mlflow.log_params({"C": 1.0, "max_iter": 200})mlflow.log_metrics({"accuracy": 0.93, "f1": 0.92}, step=0)mlflow.set_tags({"stage": "exploration", "owner": "data-science"})
Prefer the batch forms when you log many values, because each single call is a network request to the tracking server.
Parameters
A parameter records an input that you want to remember. Log every value that could change the result: hyperparameters, the feature list, the random seed, and an identifier for the training data.
MLflow stores parameter values as strings. log_param("C", 1.0) stores "1.0", and a list or dictionary is stored as its str() form. Logging a dictionary directly as one value works, but you cannot filter on its parts. Flatten it into separate keys instead.
Parameters are write-once. If you log a different value under a key that already exists in the same run, MLflow raises an error:
import mlflow
from mlflow.exceptions import MlflowException
with mlflow.start_run(run_name="param-immutable"):
mlflow.log_param("C", 1.0)
mlflow.log_param("C", 1.0) # same value: allowed
try:
mlflow.log_param("C", 10.0) # different value: rejected
except MlflowException as err:
print("Rejected:", err.message)This restriction is deliberate. A parameter is a statement of what the run used, so it must not change after the fact. If you find yourself wanting to update a parameter, you probably want a metric (which can change) or a new run.
There is also a length limit on values. Recent MLflow versions allow several thousand characters, and older ones allow far fewer. Do not log a whole config file as a parameter. Save it as an artifact instead, which the artifacts chapter covers.
Metrics
A metric is a number you measure. Unlike parameters, you can log the same metric key many times. Each call stores a value, a timestamp and a step. The step is an integer you choose, usually the epoch or iteration number. The UI uses it for the x-axis of line charts.
The next example trains incrementally and logs a metric series per epoch. It also logs the parameters once, up front.
import mlflow
import numpy as np
from sklearn.datasets import load_iris
from sklearn.linear_model import SGDClassifier
from sklearn.model_selection import train_test_split
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
classes = np.unique(y)
params = {"loss": "hinge", "alpha": 0.0001, "epochs": 20}
clf = SGDClassifier(loss=params["loss"], alpha=params["alpha"], random_state=42)
with mlflow.start_run(run_name="sgd-epochs") as run:
mlflow.log_params(params)
for epoch in range(params["epochs"]):
clf.partial_fit(X_train, y_train, classes=classes)
mlflow.log_metrics(
{
"train_accuracy": clf.score(X_train, y_train),
"test_accuracy": clf.score(X_test, y_test),
},
step=epoch,
)
mlflow.set_tags({"stage": "exploration", "dataset": "iris"})
print(run.info.run_id)After this run, the experiment UI shows two curves. The run's summary table shows the latest value of each metric, which here is the value at step 19.
You can read the values back. mlflow.get_run(run_id).data.metrics returns only the latest value per key. To get the whole series, use the client:
from mlflow import MlflowClient
client = MlflowClient()
history = client.get_metric_history(run.info.run_id, "test_accuracy")
for point in history[:3]:
print(point.step, point.value)Metric rules to remember
- Values must be numbers. Log
0.93, not"93%". - Keys are case-sensitive, so
Accuracyandaccuracyare two different metrics. - Use consistent names across runs. Comparison and
search_runswork by key, sotest_accin one run andtest_accuracyin another will not line up. - If you omit
step, it defaults to 0. Logging the same key repeatedly without steps puts every point at step 0, and the chart is unreadable. Passstepwhenever you log a series. - Log a final summary metric under its own key, such as
test_accuracy, in addition to any per-epoch series. Sorting runs by the last point of a noisy series is a common source of wrong "best run" choices.
Tags
Tags are labels. They are strings, and you can overwrite them at any time, so they suit information that is about the run rather than part of what it computed.
import mlflow
with mlflow.start_run(run_name="tagged") as run:
mlflow.set_tag("stage", "exploration")
mlflow.set_tags({"owner": "data-science", "ticket": "ML-142"})
# Later, after review, change the same tag on the finished run
mlflow.MlflowClient().set_tag(run.info.run_id, "stage", "reviewed")The last line shows that tags can be edited after a run ends. Parameters and metrics cannot be edited that way.
MLflow also sets system tags itself, and their keys start with mlflow.. Examples are mlflow.user (who ran it), mlflow.runName and mlflow.source.name (the notebook or script). Do not use the mlflow. prefix for your own tags, because some of those keys have special meaning.
Choosing between the three
When you are unsure where a value belongs, ask two questions.
- Did you decide it before the run, or did the run produce it? Decided values are parameters. Produced numbers are metrics.
- Might you need to correct it later? If yes, it is a tag.
Some cases are not obvious:
- Training time in seconds is a metric, because the run measured it.
- The model class name, such as
LogisticRegression, is a parameter, because you chose it. - "Approved by Maria" is a tag, because it is a label that may change.
- The number of rows in the training set is usually a parameter if it describes the input, and a metric if you want to chart it across runs. Pick one and stay consistent.
Common errors
- A parameter conflict error on re-run. You logged a changed value for the same key within one run. Start a new run for each configuration.
- A flat line or one dot in the metric chart. You did not pass
step, so all points share step 0. - Logging goes to the wrong experiment. You called
set_experimentafter the run started, or in another cell that did not run. Set the experiment first, and printmlflow.get_experiment_by_name(...)to confirm. - Filters match nothing. Tag and parameter values are strings. A filter such as
params.C = '1.0'needs quotes, andmetrics.accuracy > 0.9does not. - Very slow loops. Logging one metric per call inside a tight loop makes many requests. Batch with
log_metrics, or log every N steps.
Exercise
You train for 50 epochs and call mlflow.logmetric("loss", value) once per epoch without a step argument. Then you try mlflow.logparam("epochs", 50) at the start and mlflow.log_param("epochs", 60) at the end of the same run. What happens in the UI and in the code?
Show answer
The loss chart shows all 50 points stacked at step 0, so there is no curve. Pass step=epoch to fix it. The second log_param call with a different value for "epochs" raises an MlflowException because parameters are write-once within a run. Log the real epoch count once, or log the number of epochs actually completed as a metric.