Sub topic 2
Letting Autologging Do the Work
This chapter assumes basic Python, context managers, scikit-learn model training, and train/test splits. It also assumes access to a Databricks notebook with MLflow available.
Autologging
Autologging is MLflow’s automatic logging feature. After you enable the integration for a library, MLflow records common parameters, training metrics, and often the trained model during fit().
Use manual logging when a value is specific to your workflow, such as a test-set metric or a business label.
import mlflow
from mlflow.models import infer_signature
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
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, test_size=0.25, random_state=42
)
with mlflow.start_run(run_name="autolog-logreg") as run:
model = LogisticRegression(max_iter=200).fit(X_train, y_train)
mlflow.log_metric("test_accuracy", model.score(X_test, y_test))
mlflow.log_text("Iris baseline trained with LogisticRegression", "notes.txt")
signature = infer_signature(X_train, model.predict(X_train))
mlflow.sklearn.log_model(
model,
artifact_path="model",
signature=signature,
input_example=X_test[:5],
)
print(run.info.run_id)log_models=False prevents autologging from creating a second model artifact. The example logs the model explicitly so it can include a signature and input example.
Artifacts
An artifact is a file associated with a run. Examples include a model, plot, data sample, or text report. In the example, notes.txt and the model directory are artifacts. Open a run in the Databricks experiment UI to browse them.
Model Signatures and Input Examples
A model signature describes the expected input and output structure. infer_signature() derives it from example data. An input example shows the shape and type of data that the model expects. Together, they help detect incompatible inputs before deployment.
Comparing Runs in the UI
Each run appears in the experiment’s run table. Select runs to compare parameters, metrics, tags, source information, and artifacts. Sort by test_accuracy, then inspect whether the best score came from a reasonable configuration. A higher metric alone does not prove that a model is suitable.
Exercise
Why might you disable model autologging before calling log_model() yourself?
Show answer
To avoid duplicate model artifacts and to attach a specific signature and input example to the model you keep.