Sub topic 4
Logging parameters, metrics and tags
This chapter covers the three kinds of small, searchable values you attach to a run: parameters, metrics and tags. You will learn what each one is for, how MLflow stores it, and which mistakes cause errors or confusing results later.
It assumes you can write a Python script with context managers and train a scikit-learn model. It also assumes you have the local tracking server from the earlier chapter running at http://127.0.0.1:5000.
Three kinds of values, three jobs
Each run holds three kinds of small key-value records. They look similar in code, but MLflow treats them differently, and that affects how you search and compare runs.
| Kind | Describes | Value type | Can change after logging? | Typical example |
|---|---|---|---|---|
| Parameter | An input you chose before or at the start of training | Stored as a string | No, one value per key per run | `C`, `learning_rate`, `random_state` |
| Metric | A numeric result measured during or after training | Float | Yes, you can log more values over time | `test_accuracy`, `train_loss` |
| Tag | A label about the run | String | Yes, overwritten by calling again | `stage`, `owner`, `git_commit` |
A rule of thumb: if you would need to know it to reproduce the run, it is a parameter. If you would use it to judge the run, it is a metric. If you would use it to find or organize the run, it is a tag.
Parameters
A parameter records one input to a run. You log it with mlflow.log_param(key, value) inside an active run.
import mlflow
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
mlflow.set_tracking_uri("http://127.0.0.1:5000")
mlflow.set_experiment("iris-baseline")
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
C = 1.0
with mlflow.start_run(run_name="logreg-c1"):
model = LogisticRegression(C=C, max_iter=200).fit(X_train, y_train)
mlflow.log_param("C", C)
mlflow.log_param("random_state", 42)
mlflow.log_metric("test_accuracy", model.score(X_test, y_test))
mlflow.set_tag("stage", "baseline")When you have many parameters, mlflow.log_params({...}) logs a whole dictionary in one call. It is shorter and sends fewer requests to the server.
Parameters are strings and are write-once
MLflow converts every parameter value to a string. You log C = 1.0, and the UI and search_runs give you back "1.0". If you filter on a parameter you must compare strings, for example params.C = '1.0'. A numeric comparison such as params.C > 0.5 does not work as you might expect. If you need to sort or filter by number, log that value as a metric as well, or add a numeric tag.
A parameter key can be logged only once per run with one value. Logging the same key again with the same value is harmless. Logging it with a different value raises an MlflowException:
import mlflow
from mlflow.exceptions import MlflowException
with mlflow.start_run():
mlflow.log_param("C", 1.0)
mlflow.log_param("C", 1.0) # same value, accepted
try:
mlflow.log_param("C", 10.0) # different value, rejected
except MlflowException as err:
print("Rejected:", err)The restriction is deliberate. A parameter says what the run was configured with, so letting it change would make the record unreliable. If your code sets C in one place and later overrides it, you will see this error. The fix is to log parameters once, after the final configuration is known, not scatter log_param calls through the training code.
What to log as parameters
- Hyperparameters such as
C,n_estimatorsandmax_depth. - Data choices such as the random seed, split ratio, dataset version and feature list name.
- Preprocessing choices such as the scaler type or imputation strategy.
Avoid logging large objects. Parameter values have a length limit, and the exact limit has changed between MLflow versions, so check the release you use. If a value is long, such as a full config file, save it as an artifact with mlflow.log_dict (covered in the next chapter) and log only a short identifier or file name as a parameter.
Metrics
A metric is a numeric measurement. You log it with mlflow.log_metric(key, value). The value must be a number that can be converted to a float.
A metric differs from a parameter in an important way: MLflow keeps a history of every value you log for a key. Each entry carries a value, a step and a timestamp. The step is an integer you supply, usually the epoch or iteration number. If you leave it out, it defaults to 0.
Stepwise metrics
To track how a value changes during training, pass step on each call:
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
mlflow.set_tracking_uri("http://127.0.0.1:5000")
mlflow.set_experiment("iris-stepwise")
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
clf = SGDClassifier(random_state=0)
with mlflow.start_run(run_name="sgd-epochs"):
mlflow.log_param("model", "SGDClassifier")
for epoch in range(5):
clf.partial_fit(X_train, y_train, classes=np.unique(y))
mlflow.log_metric("val_accuracy", clf.score(X_test, y_test), step=epoch)In the UI, a metric with several steps appears as a line chart on the run's page. A metric logged once shows as a single number.
Reading metrics back
The run object holds only the latest value of each metric, which is the value with the highest step. To get the full history, ask the client:
import mlflow
from mlflow import MlflowClient
mlflow.set_tracking_uri("http://127.0.0.1:5000")
client = MlflowClient()
experiment = client.get_experiment_by_name("iris-stepwise")
run = client.search_runs([experiment.experiment_id], max_results=1)[0]
print("Latest values:", run.data.metrics)
for point in client.get_metric_history(run.info.run_id, "val_accuracy"):
print(point.step, point.value)This difference matters when you compare runs. A column named metrics.val_accuracy in search_runs is the final logged value, not the best one. If your model peaked at epoch 3 and got worse by epoch 5, the comparison shows epoch 5. Log a separate metric such as best_val_accuracy if you want to compare peaks.
Several metrics at once
mlflow.log_metrics({"precision": 0.93, "recall": 0.91}) logs a dictionary in one call, and it accepts a step argument too. Use it at the end of an evaluation to record all results together.
Naming metrics
Metric names may contain letters, digits, underscores, dashes, periods, spaces and slashes. Some other characters are rejected. Choose names with a consistent scheme, because the UI and search_runs match on exact keys. These conventions help:
- Separate the data split from the measure, with the split first or last, and keep it the same everywhere:
train_loss,val_loss,test_accuracy. - Do not change a name partway through a project.
val_accin one run andvalidation_accuracyin another cannot be compared on the same chart or in the same filter. - Log the same metric for every run in an experiment, so each run appears in every comparison.
Common metric mistakes
- Logging the same key twice without a step. Both values go to step 0, so you get two points at the same step and a confusing chart. Use
stepwhenever you log a key more than once. - Logging a non-number. Passing a string such as
"0.93"fails or behaves unpredictably. Convert withfloat()first. NumPy scalars generally work, but arrays do not. - Treating a metric as a parameter. If a number is an input, such as the learning rate, log it as a parameter. Otherwise it appears in the metric columns and gets compared as if it were a result.
Tags
A tag is a string key and a string value that describes a run. You set one with mlflow.set_tag(key, value) and several with mlflow.set_tags({...}).
Unlike parameters, tags are mutable. Calling set_tag again with the same key overwrites the value. This makes tags the right place for information that changes over a run's life, such as a review status:
import mlflow
mlflow.set_tracking_uri("http://127.0.0.1:5000")
mlflow.set_experiment("iris-baseline")
with mlflow.start_run(run_name="tagged-run") as run:
mlflow.set_tags({
"stage": "baseline",
"owner": "dana",
"dataset_version": "iris-2024-01",
})
# Later, from another script, update a tag on the finished run.
client = mlflow.MlflowClient()
client.set_tag(run.info.run_id, "review", "approved")The last call shows another difference. You can change tags on a finished run through the client, but you cannot add parameters to it or change them.
System tags
MLflow reserves tag names that start with mlflow.. A few are useful to know:
mlflow.runNameholds the run's display name. Settingrun_nameinstart_runwrites this tag.mlflow.note.contentholds the free-text description shown in the UI. You can set it from code to leave a note for teammates.mlflow.source.git.commitand similarmlflow.source.*tags are filled in automatically when MLflow can detect the source of the run.
Do not write your own tags with the mlflow. prefix, unless you intend to use one of these documented names.
What to tag
Tags work well for facts that identify or group runs:
- Project phase:
stage = baseline,stage = tuning. - Ownership:
owner,team. - Provenance not captured automatically:
dataset_version,pipeline_id. - Workflow state:
review = approved.
Filter on tags with tags.stage = 'baseline' in the UI search box or in search_runs. This works because a tag is a plain string, so exact comparison is reliable. Agree on spelling and case with your team, because Baseline and baseline are different values.
Choosing between them: a worked example
Suppose you train a model with a 0.2 test split and seed 42, using a dataset prepared on a given date. You get an accuracy of 0.97 and want to mark the run as the current candidate. Here is how each item is recorded:
| Item | Record as | Reason |
|---|---|---|
| `test_size = 0.2` | Parameter | A chosen input, needed to reproduce the run |
| `random_state = 42` | Parameter | A chosen input |
| `test_accuracy = 0.97` | Metric | A measured result |
| `dataset_version = 2024-01` | Tag | Identifies the data, used to group runs |
| `candidate = true` | Tag | State that may change later |
The dataset version could also be a parameter, and many teams do that. The choice depends on whether you want it treated as part of the configuration, which makes it write-once, or as a label you can correct. Pick one convention and keep it.
Common errors
MlflowExceptiononlog_param. You logged the same key with a different value. Log each parameter once.- No active run.
log_metricoutside awith mlflow.start_run()block starts a run implicitly in recent versions, which can leave stray runs in the default experiment. Callset_experimentand use an explicitwithblock. - Parameter filter returns nothing. Parameters are strings. Quote the value, as in
params.C = '1.0'. - Metric chart is a single dot. You logged without
step, or logged only once. - Metrics from two runs will not compare. The key names differ between runs. Standardize names.
Exercises
Exercise
A training loop calls mlflow.logmetric("valloss", loss) once per epoch for 10 epochs, with no step argument. What does the run's chart show, and how do you fix it?
Show answer
All 10 values are recorded at step 0, so the UI cannot draw a curve over epochs. Pass the epoch number: mlflow.logmetric("valloss", loss, step=epoch).
Exercise
You log mlflow.logparam("learningrate", 0.1) and later in the same run call mlflow.logparam("learningrate", 0.01). What happens, and which MLflow record type would you use for a value that is meant to change?
Show answer
The second call raises an MlflowException because a parameter key is write-once per run with a different value. Use a metric if it is a number measured over time, or a tag if it is a label that you may overwrite.
Exercise
searchruns shows metrics.valaccuracy = 0.88 for a run that reached 0.95 at epoch 3 and then declined. Why, and what should you log to rank runs by their peak?
Show answer
The run's metric value is the latest one logged, which is the highest step, not the best. Log an extra metric such as bestvalaccuracy, computed in your code, and rank on that.