Sub topic 5
Letting autologging do the work
This chapter assumes you can create runs and log parameters, metrics and tags by hand, and that you can train a scikit-learn model. It covers what autologging records, how to turn it on and tune it, and where it falls short.
What autologging is
Autologging is an MLflow feature that patches the training functions of a supported library. When you call fit, MLflow records the parameters, training metrics, and often the model itself, without you writing log_param or log_metric calls.
You enable it once, before training. The call is per library (mlflow.sklearn.autolog()) or generic (mlflow.autolog()). The generic call turns on every integration whose library is installed.
On Databricks, autologging is enabled by default in notebooks on Databricks Runtime for Machine Learning. The explicit call is still worth writing. It documents your intent and lets you pass options that change what is captured.
What gets recorded
For a scikit-learn estimator, the exact set depends on your MLflow version and the options you set. A typical fit produces the following.
| Kind | Examples |
|---|---|
| Parameters | Every constructor argument of the estimator, such as `C`, `max_iter`, `solver`, including defaults you never set |
| Metrics | Training score, for example `training_accuracy_score` for a classifier |
| Tags | The estimator class name and the autologging integration used |
| Artifacts | The fitted model, with a signature and an input example when enabled |
Two points matter here. First, defaults are logged too, so a later change to a library default shows up when you compare runs. Second, the metrics are computed on the data passed to fit. They are training metrics, so a high value says nothing about generalization.
A worked example
The next script enables autologging, trains a model, and adds a test metric by hand.
import mlflow
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
mlflow.sklearn.autolog()
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
with mlflow.start_run(run_name="autolog-logreg"):
model = LogisticRegression(max_iter=200).fit(X_train, y_train)
mlflow.log_metric("test_accuracy", model.score(X_test, y_test))Open the run in the experiment UI. You will see the parameters you set and the ones you did not, a training metric, and a model artifact. The test_accuracy metric sits beside them because both calls wrote to the same active run.
The manual log_metric call is the usual division of labor. Autologging sees only what happens inside fit. It does not know about your held-out test set, so you log evaluation results yourself.
Autologging and the run lifecycle
Autologging interacts with runs in a way that surprises people, so the rules are worth stating.
- If a run is active when
fitis called, autologging logs into it. - If no run is active, autologging starts a run, logs into it, and ends it when
fitreturns. You then cannot add a metric to that run through the normal active-run path. - Wrapping training in
with mlflow.start_run():keeps the run open, so your manual calls land in the same place.
For most scripts, always opening the run yourself is the safer habit. It also lets you name the run and set tags before training starts.
Configuring what is captured
autolog accepts arguments that control the output. These are the ones you will use most with scikit-learn.
| Argument | Effect |
|---|---|
| `log_models` | Whether to save the fitted model as an artifact. Set to `False` to skip it. |
| `log_input_examples` | Save a sample of the training input with the model. |
| `log_model_signatures` | Infer and save the input and output schema. |
| `log_datasets` | Record dataset metadata for the run. |
| `max_tuning_runs` | How many child runs to create for a search such as `GridSearchCV`. |
| `disable` | Turn autologging off for that integration. |
| `silent` | Suppress MLflow's own warnings during autologging. |
A configured call looks like this.
import mlflow
mlflow.sklearn.autolog(
log_input_examples=True,
log_model_signatures=True,
log_models=True,
max_tuning_runs=5,
)Check the argument list against your installed MLflow version. Defaults have changed across releases, and newer versions have added or renamed options.
Hyperparameter searches
Scikit-learn search objects such as GridSearchCV and RandomizedSearchCV receive special handling. Autologging creates a parent run for the search and child runs for the best candidates, up to max_tuning_runs. This resembles the manual nested-run pattern you will meet in a later chapter, with one difference. Autologging limits the children to the top results by default, so a large grid does not flood the experiment with hundreds of runs.
If you need every trial recorded, set max_tuning_runs=None. Expect slower logging and a large run list.
Other libraries
The same idea applies beyond scikit-learn. Integrations exist for libraries such as XGBoost, LightGBM, PyTorch Lightning, Keras and TensorFlow, and Spark MLlib. The recorded details differ by library. Deep learning integrations typically log a metric per epoch, which produces a curve in the UI. Tree libraries may log feature importance as an artifact.
Using mlflow.autolog() without a library name is convenient in exploratory notebooks. In shared or production code, name the library you mean. A generic call can start patching a library you did not intend to track.
Where autologging falls short
Autologging is a starting point. Know its limits before you rely on it.
- No evaluation on held-out data. It records training metrics only. Add test or validation metrics manually, as in the example above.
- No business context. It cannot know your dataset version, the ticket you are working on, or why you ran the experiment. Add tags for that.
- Only the supported call paths are patched. Training through a custom loop or a wrapper that bypasses the library's standard
fitmay log nothing. Check the UI after the first run. - Noise. Logging every parameter and every cross-validation fold can hide the few values you care about. Sort and filter in the UI, or narrow what is logged.
- Model logging cost. Saving a large model on every
fittakes time and storage. Uselog_models=Falseduring rapid iteration, then log the final model explicitly with a signature and input example. - Silent failures. Autologging catches its own exceptions so that a logging problem does not kill your training job. The cost is that a missing artifact may produce only a warning.
Combining autologging with manual logging
A reliable pattern is to let autologging cover parameters and the model, and to log everything with meaning yourself.
import mlflow
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
mlflow.sklearn.autolog(log_models=False)
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
with mlflow.start_run(run_name="rf-baseline"):
mlflow.set_tag("data_version", "iris-v1")
mlflow.set_tag("stage", "exploration")
rf = RandomForestClassifier(n_estimators=100, random_state=42)
rf.fit(X_train, y_train)
mlflow.log_metric("test_accuracy", rf.score(X_test, y_test))Here log_models=False keeps the run light. The tags tie the run to a data version, and the test metric is the one you will rank by. When a run proves worth keeping, you log its model explicitly, which the next chapters cover.
Common errors
- Autologging called after training. The patch applies only to later
fitcalls. Enable it before you train. - Expecting the test metric to appear. Only
fitis instrumented. Callingmodel.score(X_test, y_test)does not log a result unless you use the evaluation features of your library and have them enabled, or log it yourself. - Autologging enabled twice with different options. The most recent call wins for that integration. Keep one call near the top of the notebook.
- A run that closed too early. If you call
fitoutsidestart_run, the run ends whenfitreturns, and your follow-uplog_metriccreates a second run. Open the run first.
Exercise
You call mlflow.sklearn.autolog() and then run model = LogisticRegression().fit(X_train, y_train) with no with mlflow.start_run() block. Right after, you call mlflow.log_metric("test_accuracy", 0.94). Where does the metric end up, and how do you fix it so the parameters, the model and the metric are in one run?
Show answer
Autologging creates a run for the fit and ends it when fit returns, so the metric is logged to a new run created by logmetric, not to the autologged run. Wrap the fit and the logmetric call in a single with mlflow.start_run(): block so both use the same active run.
Exercise
A teammate ranks runs by training_accuracy_score from autologging and picks the top one for deployment. Name the problem and one change that fixes it.
Show answer
The metric is computed on the training data, so it rewards overfitting and says little about performance on unseen data. Log a held-out metric such as test_accuracy with mlflow.log_metric, and rank runs by that metric.