Sub topic 8
Comparing runs in the experiment UI
This chapter shows how to use the Databricks experiment page to decide which run is best and why. It assumes you can already create runs and log parameters, metrics and tags with the MLflow Python API. It also assumes you have an experiment with several runs in it. If you don't, the code below creates some.
What comparison is for
Comparison answers two different questions:
- Which run scored best on a metric?
- Which parameter changes caused the difference?
The first needs sorting and filtering. The second needs side-by-side views. The experiment page supports both, and the choice of view depends on how many runs you have.
Generate runs worth comparing
A comparison is only useful when runs differ in more than one parameter. This script logs 12 runs that vary the regularization strength C and the solver. Each run logs a training metric and a test metric, so you can also spot overfitting.
import mlflow
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
mlflow.set_experiment("/Users/<your-email>/iris-tracking")
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
for solver in ["lbfgs", "liblinear", "newton-cg"]:
for c in [0.01, 0.1, 1.0, 10.0]:
with mlflow.start_run(run_name=f"{solver}-C{c}"):
model = LogisticRegression(C=c, solver=solver, max_iter=200)
model.fit(X_train, y_train)
mlflow.log_param("C", c)
mlflow.log_param("solver", solver)
mlflow.log_metric("train_accuracy", model.score(X_train, y_train))
mlflow.log_metric("test_accuracy", model.score(X_test, y_test))
mlflow.set_tag("stage", "exploration")Run it, then open the experiment from the Experiments page in the workspace sidebar, or from the flask icon in the notebook.
The experiment page: table view
The default view is a table with one row per run. Columns include the run name, creation time, the user, and the source. Further columns appear for each logged metric and parameter.
Three controls do most of the work.
Columns
Use the column selector to show or hide metrics, parameters and tags. Show only the ones you are comparing, such as C, solver and test_accuracy. A table with 40 columns hides the signal.
Sorting
Click a column header to sort by it. Sort by test_accuracy descending to put the best run on top. Sorting is the fastest way to get a ranking, but it says nothing about why the top run won.
Filtering
The search box accepts a filter string. The syntax is the same one mlflow.search_runs takes, so a filter you refine in the UI can be pasted into code later.
metrics.test_accuracy > 0.9
params.solver = 'lbfgs' and metrics.test_accuracy > 0.9
tags.stage = 'exploration'
attributes.status = 'FINISHED'Some details matter here:
- Parameters are always stored as strings. Compare them with quotes, as in
params.C = '1.0'. Numeric operators on parameters do not work as they do on metrics. - Metric names that contain special characters need backticks around the name.
- String values use single quotes.
The UI also has dropdown filters for time created and for run state. Use them to hide failed or running runs while you compare.
Chart view
Switch from Table to Chart to see all visible runs plotted together. Chart view is useful for scanning many runs, because patterns are easier to see than numbers.
| Chart | Shows | Best for |
|---|---|---|
| Bar chart | One metric across runs | Ranking a handful of runs |
| Line chart | A metric over steps | Comparing training curves |
| Scatter plot | One metric against another, or a parameter against a metric | Checking the effect of one parameter |
| Parallel coordinates | Several parameters and metrics at once | Finding which parameter combinations give high metrics |
| Contour plot | Two parameters against one metric | Looking for a smooth optimum |
The set of chart types and their names changes between Databricks releases. If a chart is missing, look for it under the chart-adding control in the chart view.
Line charts only show anything when you logged a metric with a step. Metrics logged once per run, as in the script above, appear as a single point. To get a curve, log inside a loop:
import mlflow
with mlflow.start_run(run_name="curve-demo"):
for epoch in range(10):
mlflow.log_metric("loss", 1.0 / (epoch + 1), step=epoch)Reading parallel coordinates
Parallel coordinates draw one vertical axis per parameter or metric, and one line per run. Each line crosses every axis at that run's value. Drag along an axis to select a range, and the lines that pass through it are highlighted.
To read the plot:
- Select the high range on the
test_accuracyaxis. - Look at where the highlighted lines cross the
Candsolveraxes. - If they cluster at one value, that parameter likely matters. If they scatter, it probably doesn't.
With the iris runs above, you would likely see that very small C values (strong regularization) lower accuracy, while the solver makes almost no difference.
Side-by-side comparison
Tick the checkboxes of two or more runs in table view, then click Compare. The comparison page shows the selected runs together, with several parts:
- A run details table listing source, start time, duration and the run IDs.
- Parameters, metrics and tags for each run, one column per run.
- Plots such as parallel coordinates, scatter and contour, restricted to the selected runs.
The Show diff only toggle hides rows that have the same value in every run. Turn it on when you compare two runs that should be identical except for one change. The remaining rows are the differences, and they tell you what you changed, including things you forgot you changed.
A reliable habit is to compare a pair at a time: your baseline and one candidate. Comparing eight runs at once is a job for charts.
A workflow that scales
The following diagram shows how the pieces fit when you have many runs.
Step G is easy to skip. Tag the chosen run so the decision outlives your memory of it:
from mlflow import MlflowClient
client = MlflowClient()
client.set_tag("<run-id>", "selected", "true")Replace <run-id> with the ID from the run page. A tag can then be used in a filter, such as tags.selected = 'true'.
Common mistakes
Comparing runs that are not comparable
Two runs with the same metric name can still measure different things. If one run evaluated on a validation set and another on the test set, both accuracy values are valid but cannot be ranked against each other. Use distinct metric names, such as val_accuracy and test_accuracy, and keep each run's data split in a parameter or tag.
Ranking by a metric you tuned on
If you sweep hyperparameters and then pick the run with the best test_accuracy, the test score is now optimistic. You selected it because it was high. Keep a separate held-out set for the final number, or rank by validation metric and report the test metric only for the winner.
Reading the last value of a metric
Table columns show the latest value for each metric. For a metric logged per step, the best value may have been earlier. Check the line chart before trusting the column.
Runs missing from the view
Runs can be missing for several reasons:
- A filter is still applied.
- A run was deleted, and deleted runs are hidden by default.
- The runs went to a different experiment because
set_experimentwas not called, or was called with a different path. - A run is still active, so metrics are partial.
Check the experiment path first. Runs landing in the notebook's own experiment instead of the workspace experiment is a common cause.
Moving from the UI to code
The UI is good for exploring. Code is better when you want a repeatable answer. The filter string you used in the search box can be passed straight to mlflow.search_runs, which the next chapters cover in detail. This short version returns the same ranking as sorting in the table:
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[["tags.mlflow.runName", "params.C", "params.solver", "metrics.test_accuracy"]])Exercise
You sweep C and solver and want to know whether solver affects test_accuracy. Name the chart you would use and the steps you would take in it.
Show answer
Use parallel coordinates. Select the high range on the test_accuracy axis and look at where the highlighted lines cross the solver axis. If they cross at every solver value, the solver has little effect. If they cluster at one value, it matters. A scatter plot of C against test_accuracy, colored by solver, would also work.
Exercise
Why does the filter params.C > 1 not select runs the way you expect, and what are two ways to select by a numeric hyperparameter?
Show answer
MLflow stores parameters as strings, so the comparison is not numeric. Either log the hyperparameter as a metric as well and filter on metrics.C, or load runs with mlflow.search_runs and filter the pandas DataFrame after converting the column to a number.
Exercise
Two runs both report accuracy = 0.95, but one used the validation set and the other the test set. What should you change so they can be compared fairly in the UI?
Show answer
Log them under different metric names, for example val_accuracy and test_accuracy, and record the data split used for each run as a parameter or tag. Then compare only like with like.