AppUserClustering / src /streamlit_app.py
EnYa32's picture
Update src/streamlit_app.py
64657d1 verified
Raw History Blame Contribute Delete
5.21 kB
import streamlit as st
import pandas as pd
import numpy as np
import joblib
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
st.set_page_config(page_title="KMeans User Segmentation", layout="centered")
st.title("πŸ‘₯ KMeans User Segmentation")
st.write("Upload a CSV or enter values manually to assign users into **KMeans clusters**.")
# -----------------------------
# Load artifacts
# -----------------------------
@st.cache_resource
def load_artifacts():
model = joblib.load("src/kmeans_user_segmentation.pkl")
scaler = joblib.load("src/scaler.pkl")
return model, scaler
model, scaler = load_artifacts()
st.success("Model + scaler loaded successfully βœ…")
# -----------------------------
# Feature columns used in training
# -----------------------------
FEATURES = [
"Average Screen Time",
"Average Spent on App (INR)",
"Ratings",
"Last Visited Minutes",
"New Password Request",
]
# -----------------------------
# Sidebar options
# -----------------------------
st.sidebar.header("βš™οΈ Options")
input_mode = st.sidebar.radio("Input method", ["Upload CSV", "Manual Input"])
show_pca = st.sidebar.checkbox("Show PCA 2D plot (based on input data)", value=True)
# -----------------------------
# Helper: validate + prepare
# -----------------------------
def prepare_features(df: pd.DataFrame) -> pd.DataFrame:
missing = [c for c in FEATURES if c not in df.columns]
if missing:
raise ValueError(f"Missing columns: {missing}")
X = df[FEATURES].copy()
# Make sure numeric
for c in FEATURES:
X[c] = pd.to_numeric(X[c], errors="coerce")
if X.isna().any().any():
bad_cols = X.columns[X.isna().any()].tolist()
raise ValueError(f"Non-numeric or missing values found in: {bad_cols}. Please clean your CSV.")
return X
# -----------------------------
# Input: CSV
# -----------------------------
df = None
if input_mode == "Upload CSV":
uploaded = st.file_uploader("Upload CSV", type=["csv"])
if uploaded is None:
st.info("Upload a CSV to start.")
else:
df = pd.read_csv(uploaded)
st.subheader("πŸ“„ Data Preview")
st.dataframe(df.head())
# -----------------------------
# Input: Manual
# -----------------------------
else:
st.info("Manual input is best for quick testing. For real segmentation, use CSV upload.")
n = st.slider("Number of users (rows)", 1, 20, 5)
rows = []
for i in range(n):
st.markdown(f"### User {i+1}")
c1, c2 = st.columns(2)
screen_time = c1.number_input("Average Screen Time", min_value=0.0, value=10.0, key=f"st_{i}")
spent = c2.number_input("Average Spent on App (INR)", min_value=0.0, value=100.0, key=f"sp_{i}")
c3, c4 = st.columns(2)
ratings = c3.number_input("Ratings", min_value=0.0, value=7.0, key=f"ra_{i}")
last_visit = c4.number_input("Last Visited Minutes", min_value=0.0, value=1000.0, key=f"lv_{i}")
pwd_req = st.number_input("New Password Request", min_value=0.0, value=1.0, key=f"pw_{i}")
rows.append([screen_time, spent, ratings, last_visit, pwd_req])
df = pd.DataFrame(rows, columns=FEATURES)
st.subheader("πŸ“„ Manual Data")
st.dataframe(df)
# -----------------------------
# Predict
# -----------------------------
if df is not None and len(df) > 0:
try:
X = prepare_features(df)
X_scaled = scaler.transform(X)
clusters = model.predict(X_scaled)
out = df.copy()
out["cluster"] = clusters
st.subheader("βœ… Cluster Results")
st.dataframe(out.head(20))
st.subheader("πŸ“Š Cluster Distribution")
st.write(out["cluster"].value_counts().sort_index())
# Cluster profile (means)
st.subheader("πŸ“Œ Cluster Profile (mean values)")
profile = out.groupby("cluster")[FEATURES].mean(numeric_only=True).round(2)
st.dataframe(profile)
# Simple bar chart for profile
st.subheader("πŸ“ˆ Average Feature Values per Cluster")
fig, ax = plt.subplots(figsize=(9, 4))
profile.plot(kind="bar", ax=ax)
ax.set_xlabel("Cluster")
ax.set_ylabel("Mean value")
ax.legend(loc="best")
st.pyplot(fig)
# PCA plot (optional)
if show_pca and len(out) >= 3:
pca = PCA(n_components=2, random_state=42)
X_pca = pca.fit_transform(X_scaled)
st.subheader("🧭 PCA 2D Projection (Input Data)")
fig2, ax2 = plt.subplots(figsize=(6, 5))
sc = ax2.scatter(X_pca[:, 0], X_pca[:, 1], c=clusters)
ax2.set_title("KMeans Clusters (PCA Projection)")
ax2.set_xlabel("PC1")
ax2.set_ylabel("PC2")
st.pyplot(fig2)
# Download results
st.subheader("⬇️ Download")
csv = out.to_csv(index=False).encode("utf-8")
st.download_button("Download results CSV", csv, file_name="clustered_users.csv", mime="text/csv")
st.info("Tip: Clustering is unsupervised β€” clusters are groups with similar behavior patterns, not 'correct/incorrect' labels.")
except Exception as e:
st.error(str(e))
st.stop()