Find the Best Cosmetic Hospitals

Explore trusted cosmetic hospitals and make a confident choice for your transformation.

โ€œInvest in yourself โ€” your confidence is always worth it.โ€

Explore Cosmetic Hospitals

Start your journey today โ€” compare options in one place.

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 key components of MLflow: โœ… Tracking
โœ… Models
โœ… Model Registry
โœ… Signature + Input Example


๐Ÿš€ Objective:

Train a classification model on the Iris dataset, log everything with MLflow, and register the model.


โœ… Step-by-Step MLflow Lab on Databricks


๐ŸŽฏ Step 1: Setup (Install Required Libraries)

Run this in a cell:

%pip install scikit-learn pandas mlflow

๐ŸŽฏ Step 2: Import Libraries and Load Data

import pandas as pd
from sklearn import datasets
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
import mlflow
import mlflow.sklearn
from mlflow.models.signature import infer_signature
Code language: JavaScript (javascript)

๐ŸŽฏ Step 3: Prepare the Data

# Load Iris dataset
iris = datasets.load_iris()
X = iris.data
y = iris.target

# Split into training and testing
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
Code language: PHP (php)

๐ŸŽฏ Step 4: Start MLflow Run and Train Model

# Start MLflow experiment run
with mlflow.start_run() as run:

    # Train the model
    model = RandomForestClassifier(n_estimators=100, max_depth=5, random_state=42)
    model.fit(X_train, y_train)

    # Make predictions and calculate accuracy
    predictions = model.predict(X_test)
    acc = accuracy_score(y_test, predictions)

    # Log parameters and metric
    mlflow.log_param("n_estimators", 100)
    mlflow.log_param("max_depth", 5)
    mlflow.log_metric("accuracy", acc)

    # Create sample input and signature
    input_example = X_test[:5]
    signature = infer_signature(X_train, model.predict(X_train))

    # Log model with signature and input example
    mlflow.sklearn.log_model(
        sk_model=model,
        artifact_path="iris_rf_model",
        input_example=input_example,
        signature=signature
    )

    # Save run_id for model registration
    run_id = run.info.run_id
    print(f"Run ID: {run_id}")
    print(f"Accuracy: {acc}")
Code language: PHP (php)

๐ŸŽฏ Step 5: Register the Model

Paste this in a new cell:

model_uri = f"runs:/{run_id}/iris_rf_model"

# Register the model under a name
model_details = mlflow.register_model(
    model_uri=model_uri,
    name="IrisClassifierModel"
)
Code language: PHP (php)

โœ… Now go to “Models” tab in Databricks, and you’ll see IrisClassifierModel with versioning.


๐ŸŽฏ Step 6: Promote the Model (via UI)

Go to:

  • Models > IrisClassifierModel
  • Click on the version (e.g., Version 1)
  • Click Stage โ†’ Choose Staging or Production

# To Promore Version1 to Production

from mlflow.tracking import MlflowClient

client = MlflowClient()
client.transition_model_version_stage(
    name="IrisClassifierModel",
    version=1,  # or the actual version you created
    stage="Production"  # or "Staging", "Archived"
)Code language: PHP (php)

OR


# Assign an alias (like @production) to the version
from mlflow.tracking import MlflowClient

client = MlflowClient()

client.set_registered_model_alias(
    name="IrisClassifierModel",
    alias="production",
    version=1
)

Code language: PHP (php)

# Run this to list your registered models:
client = MlflowClient()
models = client.list_registered_models()
for m in models:
    print(m.name)Code language: PHP (php)

๐ŸŽฏ Step 7: Load Model from Registry and Predict

Option A: If your model is in “Production” stage (via UI):

Now that the model is registered and staged, letโ€™s load it and use it:

from mlflow.pyfunc import load_model

# Load model from registry using stage name
model = load_model("models:/IrisClassifierModel/Production")

# Predict
preds = model.predict(X_test)
print(preds)Code language: PHP (php)

Option B: If you used an alias (e.g., production) instead of a stage:


from mlflow.pyfunc import load_model

# Load model using alias
model = load_model("models:/IrisClassifierModel@production")

# Predict
preds = model.predict(X_test)
print(preds)Code language: PHP (php)

๐ŸŽ‰ You Did It!

MLflow ComponentCovered โœ…
TrackingYes (log params, metrics, artifacts)
ModelsYes (logged with signature + input example)
Model RegistryYes (registered and promoted via UI)
Serving/LoadingYes (loaded from registry and used for predictions)

๐Ÿง  Bonus Tips:

  • Want to serve the model as REST API? MLflow on Databricks supports model serving.
  • Want to run this as a Project? We can convert this into an MLflow Project next.

Let me know if you want this exported as a .dbc Databricks Notebook or want to integrate with CI/CD!

Objective: Serve Your MLflow Model via REST API on Databricks

Absolutely! Since you’ve already registered the model and assigned an alias like production, youโ€™re ready to serve the model using Databricks Model Serving.

Letโ€™s go through this step-by-step, assuming you’re using a Databricks Trial or Paid workspace (not Community Edition).


๐Ÿš€ Objective: Serve Your MLflow Model via REST API on Databricks

Weโ€™ll go from registered model with alias โžœ to real-time REST endpoint โžœ to making predictions from code.


โœ… Step 1: Confirm Model Registration & Alias

You’ve already done this, but hereโ€™s a quick reference for future:

from mlflow.tracking import MlflowClient

client = MlflowClient()

# Register model (already done)
model_uri = f"runs:/{run_id}/iris_rf_model"
client.register_model(model_uri=model_uri, name="IrisClassifierModel")

# Set alias
client.set_registered_model_alias(
    name="IrisClassifierModel",
    alias="production",
    version=1
)
Code language: PHP (php)

โœ… Step 2: Enable Model Serving from Databricks UI

  1. Go to Databricks Workspace.
  2. In the left sidebar, click “Models”.
  3. Click on IrisClassifierModel.
  4. Click on Version 1 (or the version you aliased).
  5. You should see a โ€œServingโ€ or โ€œEnable Servingโ€ button.
  6. Click it, then:
    • Choose Real-time serving
    • Click Start serving

โœ… Once serving is enabled, youโ€™ll see the endpoint URL (copy it!).


โœ… Step 3: Use the REST Endpoint for Predictions

Hereโ€™s a full Python example to send test data and get predictions:

import requests
import json

# Replace with your actual endpoint from Databricks
url = "https://<your-databricks-instance>/serving-endpoints/IrisClassifierModel/invocations"

# If needed, generate a Personal Access Token from Databricks User Settings
token = "dapiXXXXXXXXXXXXXXXXXXXX"

# Headers
headers = {
    "Authorization": f"Bearer {token}",
    "Content-Type": "application/json"
}

# Input payload (match your modelโ€™s input structure)
data = {
    "dataframe_split": {
        "columns": ["sepal length (cm)", "sepal width (cm)", "petal length (cm)", "petal width (cm)"],
        "data": [[5.1, 3.5, 1.4, 0.2]]
    }
}

# Send request
response = requests.post(url, headers=headers, json=data)

# Print response
print("Prediction:", response.json())
Code language: PHP (php)

โœ… Step 4: Test It!

Run the above Python code in:

  • Databricks notebook
  • Jupyter notebook
  • Any Python script

๐Ÿ” Generate a Personal Access Token (If Needed)

  1. Click on your profile icon in the top-right corner of Databricks.
  2. Go to “User Settings” > “Access Tokens”
  3. Click Generate New Token
  4. Copy it and use it in your token variable

๐Ÿงช Example Output:

Prediction: [0]
Code language: CSS (css)

This means it predicted class 0 (e.g., Setosa for Iris dataset).


๐Ÿง  Summary of Steps:

StepAction
โœ… 1Register model and set alias (production)
โœ… 2Enable model serving in Databricks UI
โœ… 3Copy REST endpoint URL
โœ… 4Send test prediction via Python using requests

Would you like me to generate a ready-to-run notebook (.dbc) with this entire process? Or help you test it directly with your live Databricks instance?

Find Trusted Cardiac Hospitals

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

Explore Hospitals
Iโ€™m a DevOps/SRE/DevSecOps/Cloud Expert passionate about sharing knowledge and experiences. I have worked at <a href="https://www.cotocus.com/">Cotocus</a>. I share tech blog at <a href="https://www.devopsschool.com/">DevOps School</a>, travel stories at <a href="https://www.holidaylandmark.com/">Holiday Landmark</a>, stock market tips at <a href="https://www.stocksmantra.in/">Stocks Mantra</a>, health and fitness guidance at <a href="https://www.mymedicplus.com/">My Medic Plus</a>, product reviews at <a href="https://www.truereviewnow.com/">TrueReviewNow</a> , and SEO strategies at <a href="https://www.wizbrand.com/">Wizbrand.</a> Do you want to learn <a href="https://www.quantumuting.com/">Quantum Computing</a>? <strong>Please find my social handles as below;</strong> <a href="https://www.rajeshkumar.xyz/">Rajesh Kumar Personal Website</a> <a href="https://www.youtube.com/TheDevOpsSchool">Rajesh Kumar at YOUTUBE</a> <a href="https://www.instagram.com/rajeshkumarin">Rajesh Kumar at INSTAGRAM</a> <a href="https://x.com/RajeshKumarIn">Rajesh Kumar at X</a> <a href="https://www.facebook.com/RajeshKumarLog">Rajesh Kumar at FACEBOOK</a> <a href="https://www.linkedin.com/in/rajeshkumarin/">Rajesh Kumar at LINKEDIN</a> <a href="https://www.wizbrand.com/rajeshkumar">Rajesh Kumar at WIZBRAND</a> <a href="https://www.rajeshkumar.xyz/dailylogs">Rajesh Kumar DailyLogs</a>

Related Posts

Terraform Backend Tutorial

Terraform is a popular open-source infrastructure as code tool used to create and manage infrastructure resources. The state of the infrastructure resources managed by Terraform is stored…

Read More

Best Tools for Software Composition Analysis (SCA)

Hereโ€™s a clear and professional explanation of the three related concepts you asked about โ€” all of which are critical parts of secure software development, especially in…

Read More

Top 10 AI Code Review Tools in 2026: Features, Pros, Cons & Comparison

Introduction In 2026, AI code review tools have become essential for developers aiming to enhance code quality, streamline workflows, and accelerate software delivery. These tools leverage advanced…

Read More

Top 10 Expense Management Tools in 2026: Features, Pros, Cons & Comparison

Introduction Expense management tools are critical for businesses of all sizes in 2026 as they help streamline financial processes, improve budgeting, ensure compliance, and enhance financial visibility….

Read More

Top 10 Web Application Firewall (WAF) Tools in 2026: Features, Pros, Cons & Comparison

Introduction In the rapidly evolving landscape of cybersecurity, Web Application Firewalls (WAFs) have become a critical component in defending web applications from malicious attacks such as SQL…

Read More

Top 10 Endpoint Management Tools in 2026: Features, Pros, Cons & Comparison

Introduction In 2026, businesses of all sizes are increasingly reliant on a variety of devicesโ€”laptops, desktops, mobile devices, and other endpointsโ€”that connect to their networks. With the…

Read More
Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x