Sub topic 9
Querying runs programmatically
The experiment UI works well for a handful of runs. When an experiment has hundreds, you need to filter and sort them in code. This chapter covers mlflow.search_runs. It assumes you can already log parameters, metrics and tags, and that your experiment has several finished runs, such as the ones from the earlier chapters.
What search_runs returns
mlflow.search_runs queries one or more experiments and returns a pandas DataFrame with one row per run. Each logged value becomes a column with a prefix:
| Prefix | Example column | Contents |
|---|---|---|
| none | `run_id`, `status`, `start_time` | Run attributes |
| `metrics.` | `metrics.test_accuracy` | Latest value of a metric |
| `params.` | `params.C` | Parameter value, always a string |
| `tags.` | `tags.stage` | Tag value |
Because the result is a DataFrame, you can use the usual pandas tools to analyze it further.
A basic query
import mlflow
runs = mlflow.search_runs(
experiment_names=["/Users/<your-email>/iris-tracking"],
filter_string="metrics.test_accuracy > 0.9",
order_by=["metrics.test_accuracy DESC"],
max_results=5,
)
print(runs[["run_id", "metrics.test_accuracy"]])The arguments do the following:
experiment_namesorexperiment_idsselects where to search. If you give neither, MLflow searches the active experiment.filter_stringis a SQL-like condition on metrics, params, tags or attributes.order_byis a list of columns, each with an optionalASCorDESC.max_resultscaps the number of rows. Set it deliberately, because the default is very large.
Writing filter strings
The filter syntax is small but strict. Conditions are joined with AND. OR is not supported.
import mlflow
experiment = ["/Users/<your-email>/iris-tracking"]
# Parameters are stored as strings, so compare against quoted text.
by_param = mlflow.search_runs(
experiment_names=experiment,
filter_string="params.C = '1.0' AND attributes.status = 'FINISHED'",
)
# Tags and run names.
tagged = mlflow.search_runs(
experiment_names=experiment,
filter_string="tags.stage = 'exploration' AND attributes.run_name = 'baseline'",
)
print(len(by_param), len(tagged))Finding the best run and its model
A common pattern is to take the top row of a sorted query and use its run_id. For example, you can register that run's model.
import mlflow
best = mlflow.search_runs(
experiment_names=["/Users/<your-email>/iris-tracking"],
filter_string="attributes.status = 'FINISHED'",
order_by=["metrics.test_accuracy DESC"],
max_results=1,
)
if best.empty:
raise RuntimeError("No finished runs found")
best_run_id = best.loc[0, "run_id"]
print(best_run_id, best.loc[0, "metrics.test_accuracy"])You can then pass f"runs:/{best_run_id}/model" to mlflow.register_model, which a later chapter covers.
Querying nested runs
Trials from a nested sweep are ordinary runs. Each one carries the tag mlflow.parentRunId, so you can select the children of one parent:
children = mlflow.search_runs(
experiment_names=["/Users/<your-email>/iris-tracking"],
filter_string=f"tags.mlflow.parentRunId = '{parent_run_id}'",
order_by=["metrics.test_accuracy DESC"],
)Here parent_run_id is the run.info.run_id of the parent run. Without a filter like this, a query returns parents and children together.
Common errors
- Empty DataFrame. The experiment name is wrong (it must be the full workspace path), or the filter matches nothing. Print
runs.columnsto see which columns exist. - Missing column. A metric or param column appears only if at least one matching run logged it. Selecting a column that no run logged raises a
KeyError. - Unexpected old values. A metric column holds the latest logged value. If you logged a metric at several steps, the column does not show the best value.
- Too many rows. Add
max_results, or filter onattributes.status = 'FINISHED'to skip failed and running runs.
If you need run objects rather than a table, pass output_format="list". You then get a list of Run objects with run.data.metrics, run.data.params and run.info.
Exercise
You want the three finished runs with the lowest value of a metric named test_loss, but only those logged with the parameter solver set to lbfgs. Write the filter_string, the order_by list and the max_results value.
Show answer
filterstring="params.solver = 'lbfgs' AND attributes.status = 'FINISHED'", orderby=["metrics.testloss ASC"], maxresults=3. The parameter value is quoted because params are strings, and ascending order puts the lowest loss first.