The example above is a minimal end-to-end machine learning workflow on Databricks: it trains a scikit-learn logistic regression model on the Iris dataset, tracks the run with MLflow, and registers the model so it can be versioned and served. This guide explains each step, fixes the problems that stop the code working as written on current Databricks workspaces (Unity Catalog model names, MLflow 3 arguments, autologging side effects), and shows how to load the registered model back for predictions.
# Hello World ML on Databricks
import mlflow
import mlflow.sklearn
from mlflow.models import infer_signature
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
# 1. Load toy data
X, y = load_iris(return_X_y=True, as_frame=True)
# 2. Train a tiny model
model = LogisticRegression(max_iter=100).fit(X, y)
preds = model.predict(X)
# 3. Set experiment (will auto-create if not present)
mlflow.set_experiment("/Shared/hello_world_exp")
# 4. Log model with signature + input_example
with mlflow.start_run():
sig = infer_signature(X, preds)
mlflow.sklearn.log_model(
sk_model=model,
artifact_path="model",
signature=sig,
input_example=X.head(3),
registered_model_name="hello_world_model"
)
Code language: PHP (php)
What the example above does
The script covers the four building blocks of almost every MLflow workflow on Databricks. Once these are clear, larger projects follow the same pattern with real data and better models.
| Step | Code | Purpose |
|---|---|---|
| Load data | load_iris(return_X_y=True, as_frame=True) | Returns features as a pandas DataFrame (named columns) and labels as a Series, so MLflow can record column names in the signature |
| Train | LogisticRegression(...).fit(X, y) | Fits a simple three-class classifier |
| Choose experiment | mlflow.set_experiment("/Shared/hello_world_exp") | Selects a workspace experiment, creating it if it does not exist. Runs are grouped under it |
| Log and register | mlflow.sklearn.log_model(...) | Saves the model as a run artifact, records its input/output schema and a sample input, and creates a new version in the model registry |
Logging stores the model inside a specific run. Registering adds a named, versioned entry in the model registry that points to that logged model. Serving endpoints, batch inference jobs and promotion workflows reference the registered name, not the run.
Prerequisites
- A Databricks workspace and a notebook attached to a cluster running Databricks Runtime ML, or serverless compute. The ML runtime ships with
mlflowandscikit-learnalready installed. - On a standard (non-ML) runtime, install the libraries first with
%pip install mlflow scikit-learn, then rundbutils.library.restartPython(). - For Unity Catalog registration:
USE CATALOGon the catalog, andUSE SCHEMAplusCREATE MODELon the target schema. The examples below usemain.default. Change these to a catalog and schema you are allowed to write to. - Permission to create experiments in the chosen folder. If
/Sharedis locked down, use/Users/<your-user>/hello_world_expinstead.
Why the original code fails or misbehaves on current workspaces
The example above runs cleanly only on older setups. On a workspace that uses Unity Catalog as its model registry, and with recent MLflow releases, you will hit these issues:
- Model name format. Unity Catalog needs a three-level name,
catalog.schema.model. A bare name such ashello_world_modelis rejected when the registry URI isdatabricks-uc, which is the default for Unity Catalog workspaces and for MLflow 3 on Databricks. artifact_pathis deprecated. In MLflow 3.x,log_modeltakesname=instead, andartifact_pathproduces a deprecation warning. On MLflow 2.x, keepartifact_path.- Stray autologged runs. Databricks autologging is on by default for ML runtimes. Calling
.fit()outsidemlflow.start_run(), and beforeset_experiment(), creates an extra automatic run, often in the notebook's default experiment instead of/Shared/hello_world_exp. - No evaluation. The model is scored on the data it was trained on, and no metric is logged, so the run does not say how good the model is.
- Convergence. With unscaled features and
max_iter=100, thelbfgssolver may raise aConvergenceWarning.
Corrected and complete version
This version sets the registry and experiment first, trains inside the run, holds out a test set, logs a metric, and registers the model under a Unity Catalog name. Run it in a single notebook cell.
import mlflow
from mlflow.models import infer_signature
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
# Registry and experiment come first so every run lands in the right place
mlflow.set_registry_uri("databricks-uc") # Unity Catalog model registry
mlflow.set_experiment("/Shared/hello_world_exp") # created if missing
CATALOG = "main" # change to a catalog you can write to
SCHEMA = "default" # change to a schema where you have CREATE MODEL
MODEL_NAME = f"{CATALOG}.{SCHEMA}.hello_world_model"
# 1. Load toy data and hold out a test set
X, y = load_iris(return_X_y=True, as_frame=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42, stratify=y
)
with mlflow.start_run(run_name="hello_world_logreg") as run:
# 2. Train inside the run so autologging attaches to this run
model = LogisticRegression(max_iter=1000)
model.fit(X_train, y_train)
# 3. Evaluate on unseen data and log the result
test_acc = accuracy_score(y_test, model.predict(X_test))
mlflow.log_param("max_iter", 1000)
mlflow.log_metric("test_accuracy", test_acc)
# 4. Signature + input example (signature is mandatory for Unity Catalog)
signature = infer_signature(X_train, model.predict(X_train))
model_info = mlflow.sklearn.log_model(
sk_model=model,
name="model", # MLflow 2.x: use artifact_path="model"
signature=signature,
input_example=X_train.head(3),
registered_model_name=MODEL_NAME,
)
print("Run ID: ", run.info.run_id)
print("Model URI: ", model_info.model_uri)
print("Test accuracy: ", round(test_acc, 3))Code language: PHP (php)
Important lines: set_registry_uri("databricks-uc") makes the registry target explicit, so the code behaves the same on any MLflow version. stratify=y keeps class proportions equal in train and test. infer_signature records column names and types, which Unity Catalog requires before it registers a model and which serving endpoints use to validate requests.
Note: If the workspace is not enabled for Unity Catalog, replace the registry line with mlflow.set_registry_uri("databricks") and use a plain model name. That is the legacy Workspace Model Registry, so prefer Unity Catalog for new work.
Expected output and where to find the results
The cell output should contain MLflow registration messages followed by the printed values. Run IDs differ, and Iris accuracy is usually close to 1.0:
Successfully registered model 'main.default.hello_world_model'.
Created version '1' of model 'main.default.hello_world_model'.
Run ID: 3f2c...e91a
Model URI: models:/m-... (format depends on MLflow version)
Test accuracy: 1.0Code language: PHP (php)
- Run details: open Experiments in the sidebar, then
hello_world_exp, then thehello_world_logregrun. You will find parameters, thetest_accuracymetric and the model artifacts (MLmodel,conda.yaml,requirements.txt,model.pkl,input_example.json). - Registered model: open Catalog, then
main, thendefault, then Models, thenhello_world_model. Each time the cell runs again, a new version is added.
Load the registered model and predict
Unity Catalog does not use the old Staging/Production stages. It uses aliases instead. Give version 1 an alias, then load the model by that alias so downstream code never hard-codes a version number.
from mlflow import MlflowClient
client = MlflowClient(registry_uri="databricks-uc")
client.set_registered_model_alias(MODEL_NAME, "champion", 1)
loaded = mlflow.pyfunc.load_model(f"models:/{MODEL_NAME}@champion")
print(loaded.predict(X_test.head(5)))
# e.g. [0 2 1 1 0] -> 0=setosa, 1=versicolor, 2=virginicaCode language: PHP (php)
mlflow.pyfunc.load_model returns a generic wrapper with the same predict interface for every model flavour, so batch jobs and serving code do not need to know that scikit-learn is underneath. To serve the model over REST, create a Model Serving endpoint from the model page in Catalog Explorer and point it at the champion alias or a specific version.
Common errors and fixes
| Symptom | Cause | Fix |
|---|---|---|
| Registration fails with an error saying the model name must have three levels | Bare name sent to the Unity Catalog registry | Use catalog.schema.model_name |
PERMISSION_DENIED when registering | Missing USE CATALOG, USE SCHEMA or CREATE MODEL | Ask an admin for grants or switch to a schema you own |
| Error that the model signature is missing | Unity Catalog requires a signature | Pass signature= or input_example= to log_model |
Deprecation warning about artifact_path | MLflow 3.x renamed the argument | Use name="model" |
| Two runs appear for one execution | Autologging captured a .fit() call made outside the run | Train inside start_run(), or call mlflow.sklearn.autolog(disable=True) |
ConvergenceWarning: lbfgs failed to converge | Too few iterations on unscaled data | Raise max_iter or add a StandardScaler in a Pipeline |
ModuleNotFoundError: No module named 'mlflow' | Non-ML runtime | %pip install mlflow then dbutils.library.restartPython() |
Best practices once hello world works
- Wrap preprocessing and the estimator in a scikit-learn
Pipelineand log the pipeline, so serving applies the same transformations as training. - Always log evaluation metrics on held-out data, and use clear
run_namevalues so runs can be compared in the experiment UI. - Promote models by moving aliases (
challengertochampion) instead of editing consumers to point at new version numbers. - Keep separate catalogs or schemas for dev and prod, and control who can create or alias models with Unity Catalog grants.
- Move notebook code into a Databricks Job or Asset Bundle once it works, so training can be repeated on a schedule.
Frequently asked questions
Why does mlflow log_model fail with a three-level name error on Databricks?
The workspace registers models in Unity Catalog, which needs names in the form catalog.schema.model. Change registered_model_name to something like main.default.hello_world_model and make sure you have CREATE MODEL on that schema.
Do I need Databricks Runtime ML to run this example?
No, but it is the easiest option because MLflow and scikit-learn are preinstalled. On other compute, install them with %pip install mlflow scikit-learn and restart Python.
What is the difference between logging and registering a model in MLflow?
Logging saves the model as an artifact of a single run. Registering creates a named, versioned registry entry that points to the logged model, and that entry is what serving endpoints and jobs reference.
How do I replace Staging and Production stages in Unity Catalog?
Unity Catalog uses aliases instead of stages. Set an alias such as champion with MlflowClient.set_registered_model_alias and load the model with models:/catalog.schema.model@champion.
Can I run this code from my laptop instead of a Databricks notebook?
Yes. Authenticate with a Databricks CLI profile or the DATABRICKS_HOST and DATABRICKS_TOKEN environment variables, call mlflow.set_tracking_uri("databricks") and mlflow.set_registry_uri("databricks-uc"), and use an experiment path under /Users/<your-user>/.
Related tutorials
- More Machine Learning tutorials
- More Big Data tutorials
- Staff MLOps Engineer: Role Blueprint, Responsibilities, Skills, KPIs, and Career Path
I’m Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms.
I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.
Find Trusted Cardiac Hospitals
Compare heart hospitals by city and services โ all in one place.
Explore Hospitals
This short but powerful snippet is a great โHello Worldโ for anyone who wants to understand how Databricks, MLflow, and scikit-learn work together in a real ML workflow. In just a few lines, it shows how to load data, train a model, set an experiment, infer the model signature, and log everything properly into MLflow with a registered model nameโexactly the pattern youโd reuse in real projects. For beginners and busy practitioners, this kind of minimal, working example is very useful to quickly grasp experiment tracking and model registry concepts before moving on to more complex pipelines.