Want to see your ML models in action with sliders, dropdowns, and live predictions? Streamlit makes that super easy — no frontend code, just Python! Let’s build interactive dashboards for both regression and classification tasks. ๐
1️⃣ Install Libraries
!pip install streamlit scikit-learn plotly pandas numpy
2️⃣ Start Your Streamlit App
import streamlit as st
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression, LogisticRegression
from sklearn.datasets import load_iris, fetch_california_housing
from sklearn.metrics import mean_squared_error, accuracy_score
import plotly.express as px
st.set_page_config(page_title="ML Dashboards", layout="wide")
st.title("๐ง Machine Learning Dashboard")
st.sidebar.header("⚙️ Choose Task")
task = st.sidebar.radio("Select Type:", ["Regression", "Classification"])
3️⃣ Regression Dashboard — California Housing
if task == "Regression":
st.header("๐ก California Housing — Linear Regression")
data = fetch_california_housing(as_frame=True)
df = data.frame
st.write("### Dataset Preview")
st.dataframe(df.head())
X = df.drop("MedHouseVal", axis=1)
y = df["MedHouseVal"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
model = LinearRegression()
model.fit(X_train, y_train)
preds = model.predict(X_test)
mse = mean_squared_error(y_test, preds)
st.metric("Mean Squared Error", round(mse, 3))
fig = px.scatter(x=y_test, y=preds, labels={'x':'Actual', 'y':'Predicted'}, title="Actual vs Predicted Values")
st.plotly_chart(fig, use_container_width=True)
4️⃣ Classification Dashboard — Iris Dataset
if task == "Classification":
st.header("๐ธ Iris Flower Classification — Logistic Regression")
iris = load_iris(as_frame=True)
df = iris.frame
st.write("### Dataset Preview")
st.dataframe(df.head())
X = df.drop("target", axis=1)
y = df["target"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
model = LogisticRegression(max_iter=500)
model.fit(X_train, y_train)
preds = model.predict(X_test)
acc = accuracy_score(y_test, preds)
st.metric("Accuracy", f"{acc*100:.2f}%")
fig = px.scatter_3d(df, x="sepal length (cm)", y="sepal width (cm)", z="petal length (cm)",
color=df["target"].map({0:"Setosa",1:"Versicolor",2:"Virginica"}),
title="3D Flower Visualization")
st.plotly_chart(fig, use_container_width=True)
5️⃣ Add Real-Time User Prediction
if task == "Classification":
st.subheader("๐ฎ Predict Flower Type")
sl = st.slider("Sepal Length (cm)", 4.0, 8.0, 5.8)
sw = st.slider("Sepal Width (cm)", 2.0, 4.5, 3.0)
pl = st.slider("Petal Length (cm)", 1.0, 7.0, 4.3)
pw = st.slider("Petal Width (cm)", 0.1, 2.5, 1.3)
sample = np.array([[sl, sw, pl, pw]])
pred = model.predict(sample)[0]
species = iris.target_names[pred]
st.success(f"๐ผ Predicted Flower: **{species}**")
6️⃣ Run the App
# Save the file as app.py
# Run this in terminal
streamlit run app.py (or) python -m streamlit run app.py
Open the link Streamlit gives (usually http://localhost:8501) — and your ML dashboard is live ๐ฏ
Part of Response(s) should be like ๐
Regression
Classification
Classification
✅ What You Learned
- ⚙️ Use Streamlit for real-time model dashboards
- ๐ก Build a regression dashboard with metrics & charts
- ๐ธ Add interactive classification UI with sliders
- ๐ Visualize results using Plotly
Now bro, you can turn any ML model into a live web app in under 50 lines of Python ๐ฅ Next up? “Streamlit + LangChain for Agentic AI Apps” — want me to make that next?
No comments:
Post a Comment