Coding Hubs School of AI – Best AI & Full Stack Courses in Delhi NCR | 100% Placement
Limited Offer: Get 50% OFF on AI & Full Stack Courses
📞 Call Now: +91 8448811540
Back to Machine Learning Notes
Topic #2308

Streamlit for ML

Streamlit turns a Python script into an interactive web app in minutes — the fastest way to build a demo, internal tool, or stakeholder-facing interface for a trained model, without writing any HTML, CSS or JavaScript.

A Complete ML Demo App

import streamlit as st
import joblib
import numpy as np

st.title("Loan Approval Predictor")
st.write("Enter applicant details to get a prediction.")

model = joblib.load("model_pipeline.pkl")

income = st.number_input("Annual Income", min_value=0, value=45000, step=1000)
age = st.slider("Age", min_value=18, max_value=100, value=34)
credit_score = st.slider("Credit Score", min_value=300, max_value=850, value=680)

if st.button("Predict"):
    features = np.array([[income, age, credit_score]])
    prediction = model.predict(features)[0]
    probability = model.predict_proba(features)[0].max()

    if prediction == 1:
        st.success(f"Approved (confidence: {probability:.1%})")
    else:
        st.error(f"Declined (confidence: {probability:.1%})")
# Run with:
# streamlit run app.py

That's the entire app — number inputs, sliders, a button, and conditional styled output, all from a handful of Python lines with no separate frontend code.

Adding Visualizations

import matplotlib.pyplot as plt

feature_importance = model.named_steps["model"].feature_importances_
feature_names = ["income", "age", "credit_score"]

fig, ax = plt.subplots()
ax.barh(feature_names, feature_importance)
st.pyplot(fig)   # Streamlit renders any matplotlib figure directly

When Streamlit Is the Right Tool

Good FitPoor Fit
Internal demos and stakeholder walkthroughsHigh-traffic, public-facing production APIs
Quick prototyping and model exploration toolsSystems needing fine-grained control over request/response format
Data science team internal toolingAnything requiring complex, custom UI/UX beyond Streamlit's built-in widgets

Practical Use Cases

  • Showing a trained model's behavior to non-technical stakeholders interactively, without building a full frontend
  • Internal exploration and debugging tools for a data science team

Common Mistakes

  • Using Streamlit as a production API backend for another application — it's built for interactive human use, not machine-to-machine API calls; use Flask or FastAPI for that.
  • Loading the model inside code that reruns on every widget interaction instead of using @st.cache_resource to load it once.
# Cache the model load so it only happens once, not on every interaction
@st.cache_resource
def load_model():
    return joblib.load("model_pipeline.pkl")

model = load_model()

Interview Relevance

Q: "When would you use Streamlit instead of building a Flask or FastAPI service?" When the goal is a quick, interactive demo or internal tool for humans to explore a model directly — not a production API meant to be called programmatically by other systems; Streamlit trades API-style flexibility for extremely fast interactive UI development.

Practice Question

Modify the app above to add a file upload widget that lets a user upload a CSV of multiple applicants and see predictions for all of them at once.

Related ML Notes

Want to go beyond the notes?

Join Coding Hubs School of AI's Machine Learning course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available
💬 Talk to Advisor
1
WhatsApp

Latest from Our Blog

Insights on AI, Data Science, Full Stack & Career

View All Articles →