EnYa32 commited on
Commit
64657d1
Β·
verified Β·
1 Parent(s): 81efac6

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +151 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,153 @@
1
- import altair as alt
2
- import numpy as np
3
- import pandas as pd
4
  import streamlit as st
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
- """
7
- # Welcome to Streamlit!
8
-
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
-
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
15
-
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
 
 
 
1
  import streamlit as st
2
+ import pandas as pd
3
+ import numpy as np
4
+ import joblib
5
+ import matplotlib.pyplot as plt
6
+ from sklearn.decomposition import PCA
7
+
8
+ st.set_page_config(page_title="KMeans User Segmentation", layout="centered")
9
+
10
+ st.title("πŸ‘₯ KMeans User Segmentation")
11
+ st.write("Upload a CSV or enter values manually to assign users into **KMeans clusters**.")
12
+
13
+ # -----------------------------
14
+ # Load artifacts
15
+ # -----------------------------
16
+ @st.cache_resource
17
+ def load_artifacts():
18
+ model = joblib.load("src/kmeans_user_segmentation.pkl")
19
+ scaler = joblib.load("src/scaler.pkl")
20
+ return model, scaler
21
+
22
+ model, scaler = load_artifacts()
23
+ st.success("Model + scaler loaded successfully βœ…")
24
+
25
+ # -----------------------------
26
+ # Feature columns used in training
27
+ # -----------------------------
28
+ FEATURES = [
29
+ "Average Screen Time",
30
+ "Average Spent on App (INR)",
31
+ "Ratings",
32
+ "Last Visited Minutes",
33
+ "New Password Request",
34
+ ]
35
+
36
+ # -----------------------------
37
+ # Sidebar options
38
+ # -----------------------------
39
+ st.sidebar.header("βš™οΈ Options")
40
+ input_mode = st.sidebar.radio("Input method", ["Upload CSV", "Manual Input"])
41
+ show_pca = st.sidebar.checkbox("Show PCA 2D plot (based on input data)", value=True)
42
+
43
+ # -----------------------------
44
+ # Helper: validate + prepare
45
+ # -----------------------------
46
+ def prepare_features(df: pd.DataFrame) -> pd.DataFrame:
47
+ missing = [c for c in FEATURES if c not in df.columns]
48
+ if missing:
49
+ raise ValueError(f"Missing columns: {missing}")
50
+ X = df[FEATURES].copy()
51
+ # Make sure numeric
52
+ for c in FEATURES:
53
+ X[c] = pd.to_numeric(X[c], errors="coerce")
54
+ if X.isna().any().any():
55
+ bad_cols = X.columns[X.isna().any()].tolist()
56
+ raise ValueError(f"Non-numeric or missing values found in: {bad_cols}. Please clean your CSV.")
57
+ return X
58
+
59
+ # -----------------------------
60
+ # Input: CSV
61
+ # -----------------------------
62
+ df = None
63
+
64
+ if input_mode == "Upload CSV":
65
+ uploaded = st.file_uploader("Upload CSV", type=["csv"])
66
+ if uploaded is None:
67
+ st.info("Upload a CSV to start.")
68
+ else:
69
+ df = pd.read_csv(uploaded)
70
+ st.subheader("πŸ“„ Data Preview")
71
+ st.dataframe(df.head())
72
+
73
+ # -----------------------------
74
+ # Input: Manual
75
+ # -----------------------------
76
+ else:
77
+ st.info("Manual input is best for quick testing. For real segmentation, use CSV upload.")
78
+ n = st.slider("Number of users (rows)", 1, 20, 5)
79
+
80
+ rows = []
81
+ for i in range(n):
82
+ st.markdown(f"### User {i+1}")
83
+ c1, c2 = st.columns(2)
84
+ screen_time = c1.number_input("Average Screen Time", min_value=0.0, value=10.0, key=f"st_{i}")
85
+ spent = c2.number_input("Average Spent on App (INR)", min_value=0.0, value=100.0, key=f"sp_{i}")
86
+
87
+ c3, c4 = st.columns(2)
88
+ ratings = c3.number_input("Ratings", min_value=0.0, value=7.0, key=f"ra_{i}")
89
+ last_visit = c4.number_input("Last Visited Minutes", min_value=0.0, value=1000.0, key=f"lv_{i}")
90
+
91
+ pwd_req = st.number_input("New Password Request", min_value=0.0, value=1.0, key=f"pw_{i}")
92
+
93
+ rows.append([screen_time, spent, ratings, last_visit, pwd_req])
94
+
95
+ df = pd.DataFrame(rows, columns=FEATURES)
96
+ st.subheader("πŸ“„ Manual Data")
97
+ st.dataframe(df)
98
+
99
+ # -----------------------------
100
+ # Predict
101
+ # -----------------------------
102
+ if df is not None and len(df) > 0:
103
+ try:
104
+ X = prepare_features(df)
105
+ X_scaled = scaler.transform(X)
106
+
107
+ clusters = model.predict(X_scaled)
108
+ out = df.copy()
109
+ out["cluster"] = clusters
110
+
111
+ st.subheader("βœ… Cluster Results")
112
+ st.dataframe(out.head(20))
113
+
114
+ st.subheader("πŸ“Š Cluster Distribution")
115
+ st.write(out["cluster"].value_counts().sort_index())
116
+
117
+ # Cluster profile (means)
118
+ st.subheader("πŸ“Œ Cluster Profile (mean values)")
119
+ profile = out.groupby("cluster")[FEATURES].mean(numeric_only=True).round(2)
120
+ st.dataframe(profile)
121
+
122
+ # Simple bar chart for profile
123
+ st.subheader("πŸ“ˆ Average Feature Values per Cluster")
124
+ fig, ax = plt.subplots(figsize=(9, 4))
125
+ profile.plot(kind="bar", ax=ax)
126
+ ax.set_xlabel("Cluster")
127
+ ax.set_ylabel("Mean value")
128
+ ax.legend(loc="best")
129
+ st.pyplot(fig)
130
+
131
+ # PCA plot (optional)
132
+ if show_pca and len(out) >= 3:
133
+ pca = PCA(n_components=2, random_state=42)
134
+ X_pca = pca.fit_transform(X_scaled)
135
+
136
+ st.subheader("🧭 PCA 2D Projection (Input Data)")
137
+ fig2, ax2 = plt.subplots(figsize=(6, 5))
138
+ sc = ax2.scatter(X_pca[:, 0], X_pca[:, 1], c=clusters)
139
+ ax2.set_title("KMeans Clusters (PCA Projection)")
140
+ ax2.set_xlabel("PC1")
141
+ ax2.set_ylabel("PC2")
142
+ st.pyplot(fig2)
143
+
144
+ # Download results
145
+ st.subheader("⬇️ Download")
146
+ csv = out.to_csv(index=False).encode("utf-8")
147
+ st.download_button("Download results CSV", csv, file_name="clustered_users.csv", mime="text/csv")
148
+
149
+ st.info("Tip: Clustering is unsupervised β€” clusters are groups with similar behavior patterns, not 'correct/incorrect' labels.")
150
 
151
+ except Exception as e:
152
+ st.error(str(e))
153
+ st.stop()