Sub topic 3
Searching runs with search_runs
This chapter assumes you can log runs with mlflow.start_run(), log metrics and parameters, and run a local tracking server. You should also understand scikit-learn train/test splits and accuracy.
Searching runs with search_runs
mlflow.search_runs() returns the runs that match a filter as a pandas DataFrame. Use filter_string for conditions on metrics, params, and tags, and order_by to sort the results.
import mlflow
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"]])Logging models with signatures
A signature records the input and output schema of a model. Pass infer_signature the sample inputs and predictions when you call log_model. Downstream code can then reject inputs with the wrong columns or types.
> The signature is stored with the model, so it documents the expected inputs even after the training script is gone.
Nested runs for hyperparameter search
Pass nested=True to start_run to make each trial a child of a parent run. The UI then groups the trials under one entry, which keeps a sweep easy to read.
Registering models and using aliases
Passing registered_model_name to log_model creates a new version in the Model Registry. An alias such as champion points to one version, so code can load models:/iris-classifier@champion without knowing the version number. Moving the alias promotes a new model without changing the consuming code.
from mlflow import MlflowClient
client = MlflowClient()
version = client.search_model_versions("name='iris-classifier'")[0].version
client.set_registered_model_alias("iris-classifier", "champion", version)Conventions for shared, reproducible tracking
| Practice | Why it helps |
|---|---|
| Name experiments by task, such as `iris-baseline` | Teammates can find related runs |
| Set a `stage` tag on every run | Filters separate baselines from experiments |
| Log every hyperparameter as a param | A run can be reproduced from its record |
| Use aliases, not version numbers, in serving code | Promotion does not require a code change |
Exercise:
Exercise
Your query metrics.test_accuracy > 0.9 returns no runs, but the UI shows runs with accuracy 0.95. What should you check first?
Show answer
Check the experiment name and the metric key spelling. search_runs only searches the experiments you name, and the filter must use the exact metric key that was logged.