MYHOSPITALNOW.COM

Find Trusted Doctors & Hospitals

Discover healthcare providers, compare hospitals, and explore treatment options worldwide.

Free Treatment Quotes • Doctor Search • Hospital Comparison

Find Healthcare Options

www.myhospitalnow.com

Databricks: Hello world AI Code

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.

StepCodePurpose
Load dataload_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
TrainLogisticRegression(...).fit(X, y)Fits a simple three-class classifier
Choose experimentmlflow.set_experiment("/Shared/hello_world_exp")Selects a workspace experiment, creating it if it does not exist. Runs are grouped under it
Log and registermlflow.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 mlflow and scikit-learn already installed.
  • On a standard (non-ML) runtime, install the libraries first with %pip install mlflow scikit-learn, then run dbutils.library.restartPython().
  • For Unity Catalog registration: USE CATALOG on the catalog, and USE SCHEMA plus CREATE MODEL on the target schema. The examples below use main.default. Change these to a catalog and schema you are allowed to write to.
  • Permission to create experiments in the chosen folder. If /Shared is locked down, use /Users/<your-user>/hello_world_exp instead.

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 as hello_world_model is rejected when the registry URI is databricks-uc, which is the default for Unity Catalog workspaces and for MLflow 3 on Databricks.
  • artifact_path is deprecated. In MLflow 3.x, log_model takes name= instead, and artifact_path produces a deprecation warning. On MLflow 2.x, keep artifact_path.
  • Stray autologged runs. Databricks autologging is on by default for ML runtimes. Calling .fit() outside mlflow.start_run(), and before set_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, the lbfgs solver may raise a ConvergenceWarning.

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 the hello_world_logreg run. You will find parameters, the test_accuracy metric and the model artifacts (MLmodel, conda.yaml, requirements.txt, model.pkl, input_example.json).
  • Registered model: open Catalog, then main, then default, then Models, then hello_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

SymptomCauseFix
Registration fails with an error saying the model name must have three levelsBare name sent to the Unity Catalog registryUse catalog.schema.model_name
PERMISSION_DENIED when registeringMissing USE CATALOG, USE SCHEMA or CREATE MODELAsk an admin for grants or switch to a schema you own
Error that the model signature is missingUnity Catalog requires a signaturePass signature= or input_example= to log_model
Deprecation warning about artifact_pathMLflow 3.x renamed the argumentUse name="model"
Two runs appear for one executionAutologging captured a .fit() call made outside the runTrain inside start_run(), or call mlflow.sklearn.autolog(disable=True)
ConvergenceWarning: lbfgs failed to convergeToo few iterations on unscaled dataRaise 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 Pipeline and log the pipeline, so serving applies the same transformations as training.
  • Always log evaluation metrics on held-out data, and use clear run_name values so runs can be compared in the experiment UI.
  • Promote models by moving aliases (challenger to champion) 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

Find Trusted Cardiac Hospitals

Compare heart hospitals by city and services โ€” all in one place.

Explore Hospitals
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.

Related Posts

MLflow Lab: End-to-End Workflow on Databricks

Absolutely! Letโ€™s walk through a complete, step-by-step tutorial to help you understand MLflow on Databricks from start to finish, using revised and working code. We’ll cover all…

Read More

MLFlow: Basic Workflow Using HuggingFace + scikit-learn + Optuna

Letโ€™s Reset: The Right Way to Learn MLflow in 2026 ๐Ÿ”ฅ Modern Use Case: End-to-End MLflow Workflow Using HuggingFace + scikit-learn + Optuna for Experiment Tracking and…

Read More

MLflow using Laptop vs Databricks vs Azure Vs SageMaker vs Kubernetes

Parameter MLflow on Laptop Databricks MLflow Azure ML + MLflow SageMaker + MLflow MLflow on Kubernetes Setup Complexity Very Low None (Fully Managed) Medium Medium High Ease…

Read More

Learning Roadmap for MLOps and Machine Learning

Below is a structured table of problem areas, each with a primary and secondary tool recommendation to guide your learning in MLOps and Machine Learning. This table…

Read More

MLFlow Lab: Cat vs Dog Classifier

This lab trains a cat vs dog image classifier with transfer learning on a pretrained MobileNet model in TensorFlow/Keras, and uses MLflow to record each training run's…

Read More

Top 10 Experiment Tracking Platforms: Features, Pros, Cons & Comparison

Introduction Experiment Tracking Platforms help machine learning teams log, compare, visualize, reproduce, and manage AI experiments across the model development lifecycle. Modern AI teams run hundreds or…

Read More
Subscribe
Notify of
guest
1 Comment
Newest
Oldest Most Voted
Skylar Bennett
Skylar Bennett
11 months ago

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.

1
0
Would love your thoughts, please comment.x
()
x