Spaces:
Sleeping
Sleeping
File size: 5,212 Bytes
256b89c 64657d1 256b89c 64657d1 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 | 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() |