Sub topic 8
Searching runs with search_runs
This chapter assumes you can log runs with mlflow.start_run, log_param, log_metric and set_tag. It also assumes you have a tracking server running and know basic pandas. The examples reuse the iris-baseline experiment from earlier chapters.
The UI is good for looking at a handful of runs. Once an experiment holds hundreds of runs, you need to ask questions in code: which run had the best accuracy, which runs used a given tag, and which run produced the model to register. mlflow.search_runs answers these questions and returns the results as a pandas DataFrame.
What search_runs returns
A call to search_runs returns one row per run. The columns come from three sources:
- Fixed columns such as
run_id,experiment_id,status,start_time,end_timeandartifact_uri. - One column per parameter, prefixed with
params.. - One column per metric, prefixed with
metrics., and one per tag, prefixed withtags..
Parameters and tags are stored as strings. Metrics are stored as floats. If you log C = 1.0, the column params.C holds the string "1.0". Remember this when you sort or compare parameters.
The column prefixes are also the names you use inside filter strings. The key metrics.test_accuracy means the latest value of the metric named test_accuracy.
import mlflow
mlflow.set_tracking_uri("http://127.0.0.1:5000")
runs = mlflow.search_runs(
experiment_names=["iris-baseline"],
filter_string="metrics.test_accuracy > 0.9 and tags.stage = 'baseline'",
order_by=["metrics.test_accuracy DESC"],
max_results=5,
)
print(runs[["run_id", "params.C", "metrics.test_accuracy"]])The call has four parts. experiment_names limits the search to named experiments. filter_string selects rows. order_by sorts them, and max_results caps how many come back. If you omit experiment_names and experiment_ids, MLflow searches the active experiment, which is the one you last set with set_experiment (or the default experiment).
The search pipeline
The server applies the filter and the ordering before it sends rows to your client. This keeps large experiments from flooding your machine.
Because that fence must use the required info string, the diagram is given below.
Only run metadata is searched: parameters, metrics, tags and run attributes. The contents of artifacts are not searchable. If you need to find runs by something in a file, log a tag or parameter that summarizes it.
Filter string syntax
The filter string is a small query language that resembles the WHERE clause of SQL. It is not full SQL, and the differences cause most errors.
Identifiers
Every key needs a prefix that says what kind of thing it is.
| Prefix | Refers to | Example |
|---|---|---|
| `metrics.` | Latest value of a metric | `metrics.test_accuracy > 0.9` |
| `params.` | A parameter, as a string | `params.C = '1.0'` |
| `tags.` | A tag, as a string | `tags.stage = 'baseline'` |
| `attributes.` | Run fields such as `status`, `run_name`, `start_time` | `attributes.status = 'FINISHED'` |
Keys that contain dots or other special characters must be wrapped in backticks, for example `metrics.val.loss < 0.5`. Without the backticks the parser misreads the key.
Operators
Metrics support =, !=, >, >=, < and <=. Parameters and tags are strings, so they support =, !=, LIKE and ILIKE. The LIKE operator is case sensitive and uses % as a wildcard. ILIKE ignores case. Conditions are joined with AND. Support for OR is not available in the basic syntax, so run two searches and combine the results in pandas when you need it.
String values must be in single quotes. A common mistake is writing tags.stage = "baseline" with double quotes inside a double-quoted Python string, which breaks the Python literal. Use single quotes inside the filter and double quotes outside, as in the example above.
Comparing parameters
Because params.C is a string, a filter such as params.C > 1 is invalid. The comparison operators for parameters are limited to the string operators above. Two practical fixes follow:
- Filter on equality, for example
params.C = '1.0'. The text must match exactly how the value was stored. - Fetch the rows, then convert in pandas with
runs["params.C"].astype(float)and filter there.
Ordering and limits
order_by takes a list of strings. Each has a key and an optional direction, such as metrics.test_accuracy DESC or attributes.start_time ASC. When you give several keys, later keys break ties.
import mlflow
runs = mlflow.search_runs(
experiment_names=["iris-baseline"],
filter_string="attributes.status = 'FINISHED'",
order_by=["metrics.test_accuracy DESC", "attributes.start_time DESC"],
max_results=10,
)
best = runs.iloc[0]
print(best["run_id"], best["metrics.test_accuracy"])Filtering on attributes.status = 'FINISHED' is a good habit. A run that crashed or was killed can leave a partial metric value that looks good but does not describe a completed training job.
If you leave out order_by, results come back with the most recent runs first. If a run has no value for the ordering key, its position depends on the backend store, so do not rely on it. Add a filter such as metrics.test_accuracy >= 0 to drop runs that never logged the metric.
The latest metric and stepwise metrics
When you log a metric with step, the run keeps a history. The metrics. columns in search_runs show only the most recently logged value, not the best one. If a model peaked at epoch 8 and degraded by epoch 20, the column shows the epoch 20 value.
Two ways to handle this:
- Log a separate summary metric, such as
best_val_loss, at the end of training. It is then searchable and sortable. - Fetch the history for one run with the client.
from mlflow import MlflowClient
client = MlflowClient()
history = client.get_metric_history("RUN_ID_HERE", "train_loss")
for m in history:
print(m.step, m.value)Replace RUN_ID_HERE with a real run_id from a search result. get_metric_history returns a list of metric objects, each with step, value and timestamp.
Output formats
By default search_runs returns a pandas DataFrame. The output_format argument can change this. Passing output_format="list" returns a list of Run objects, which gives you run.info, run.data.params and run.data.metrics instead of flat columns. Use the list form when you want typed access or when pandas is not installed.
import mlflow
runs = mlflow.search_runs(
experiment_names=["iris-baseline"],
order_by=["metrics.test_accuracy DESC"],
max_results=3,
output_format="list",
)
for run in runs:
print(run.info.run_name, run.data.params.get("C"), run.data.metrics.get("test_accuracy"))Use .get because a run may lack a given parameter or metric. Indexing with brackets raises KeyError for runs that never logged it.
Searching several experiments and nested runs
You can pass several names in experiment_names, or a list of experiment_ids. This helps when a team splits work across experiments but wants one ranked list.
Nested runs, which you created for hyperparameter sweeps, are ordinary runs in search results. Each child has a tag mlflow.parentRunId. A search over a sweep returns the parent and every child unless you filter. To get only the children of one parent:
import mlflow
parent_id = "PARENT_RUN_ID"
children = mlflow.search_runs(
experiment_names=["iris-search"],
filter_string=f"tags.mlflow.parentRunId = '{parent_id}'",
order_by=["metrics.test_accuracy DESC"],
)
print(children[["tags.mlflow.runName", "params.C", "metrics.test_accuracy"]])The parent run often has no metrics of its own, so ordering by a metric pushes it to an unpredictable place. Filtering on mlflow.parentRunId removes it.
Because the parent id is interpolated into the filter, only use ids that came from MLflow itself. Never paste user input into a filter string.
Run states and the run view type
By default, search_runs returns only active runs. Runs you deleted in the UI are in a deleted state and are hidden. The run_view_type argument takes ACTIVE_ONLY, DELETED_ONLY or ALL. Use ALL for audits, or DELETED_ONLY to find a run you removed by mistake before the server purges it.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Empty DataFrame | Wrong experiment, or a filter that matches nothing | Check `experiment_names`, then drop conditions one at a time |
| `Invalid filter string` | Missing prefix, double quotes around values, or unescaped special characters | Use `params.`, `metrics.` or `tags.`, single quotes, and backticks |
| `params.C > 1` rejected | Parameters are strings | Convert in pandas after fetching |
| Column missing from the DataFrame | No returned run logged that key | Check with `"params.C" in runs.columns` |
| Best metric not found | The column holds the last step, not the best | Log a summary metric at the end of training |
| Only 1000 rows when you expect more | `max_results` is capped by a default | Set `max_results` explicitly, and paginate if needed |
The default for max_results is 100000 in the fluent API, but backends and servers may enforce their own page size. Always set it explicitly in scripts that others depend on, so the behavior does not change silently.
Using search results in a workflow
A frequent use is to pick the best run and register its model. The run id from the DataFrame builds the model URI that the registry accepts.
import mlflow
best = mlflow.search_runs(
experiment_names=["iris-registry"],
filter_string="attributes.status = 'FINISHED'",
order_by=["attributes.start_time DESC"],
max_results=1,
).iloc[0]
model_uri = f"runs:/{best['run_id']}/model"
print(model_uri)The form runs:/<run_id>/<artifact_path> points at a logged model inside a run. The next chapters show how to register such a URI and attach an alias. Choosing a model by a query rather than by hand makes the choice repeatable, and you can record the filter you used in a tag.
Exercise
A run logged train_loss at steps 0 to 19, and the loss was lowest at step 11. You search with order_by=["metrics.train_loss ASC"]. Which value does the sort use, and how would you make the search find the run by its lowest loss?
Show answer
The sort uses the latest logged value, which is the one at step 19, not the minimum at step 11. To search by the lowest loss, log a summary metric such as min_train_loss at the end of the run (computed from the history), then order by metrics.min_train_loss ASC.
Exercise
Write a search_runs call that returns up to 3 finished runs in the experiment iris-baseline whose tag stage is baseline, best test_accuracy first. Why can you not add params.C > 1 to the filter?
Show answer
mlflow.searchruns(experimentnames=["iris-baseline"], filterstring="attributes.status = 'FINISHED' and tags.stage = 'baseline'", orderby=["metrics.testaccuracy DESC"], maxresults=3). Parameters are stored as strings, so numeric comparison operators are not supported on them. Fetch the rows and convert params.C with astype(float) in pandas, or filter with an exact string match such as params.C = '1.0'.