gamaba commited on
Commit
575ed06
Β·
verified Β·
1 Parent(s): 154fbe4

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +210 -0
app.py ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import matplotlib
3
+ matplotlib.use('Agg') # Non-interactive backend for Gradio
4
+ import matplotlib.pyplot as plt
5
+ import numpy as np
6
+ import joblib, json
7
+
8
+ # Load saved artifacts
9
+ kmeans_loaded = joblib.load('kmeans_model.pkl')
10
+ scaler_loaded = joblib.load('scaler.pkl')
11
+ with open('cluster_names.json') as f:
12
+ cluster_names_loaded = {int(k): v for k, v in json.load(f).items()}
13
+ with open('cluster_insights.json') as f:
14
+ insights_loaded = {int(k): v for k, v in json.load(f).items()}
15
+
16
+ SEGMENT_COLORS = {
17
+ 0: '#FF6B6B', 1: '#4ECDC4', 2: '#45B7D1', 3: '#96CEB4', 4: '#FFEAA7'
18
+ }
19
+ SEGMENT_EMOJIS = {0: '⚠️', 1: 'πŸš€', 2: 'πŸ§‘β€πŸ’Ό', 3: 'πŸ’°', 4: 'πŸ‘‘'}
20
+
21
+
22
+ def make_radar_chart(cluster_id):
23
+ """Generate a radar chart for the predicted cluster."""
24
+ centers = (kmeans_loaded.cluster_centers_ - kmeans_loaded.cluster_centers_.min(axis=0)) / \
25
+ (kmeans_loaded.cluster_centers_.max(axis=0) - kmeans_loaded.cluster_centers_.min(axis=0))
26
+
27
+ categories = ['Age', 'Annual Income', 'Spending Score']
28
+ angles = np.linspace(0, 2 * np.pi, len(categories), endpoint=False).tolist()
29
+ angles += angles[:1]
30
+
31
+ fig, ax = plt.subplots(figsize=(4, 4), subplot_kw=dict(polar=True))
32
+ fig.patch.set_facecolor('#1a1a2e')
33
+ ax.set_facecolor('#16213e')
34
+
35
+ for i in range(len(centers)):
36
+ vals = centers[i].tolist() + [centers[i][0]]
37
+ color = SEGMENT_COLORS[i]
38
+ lw = 3 if i == cluster_id else 1
39
+ alpha_fill = 0.4 if i == cluster_id else 0.05
40
+ ax.plot(angles, vals, 'o-', linewidth=lw, color=color,
41
+ label=cluster_names_loaded[i], alpha=1.0 if i == cluster_id else 0.4)
42
+ ax.fill(angles, vals, alpha=alpha_fill, color=color)
43
+
44
+ ax.set_thetagrids(np.degrees(angles[:-1]), categories, color='white', fontsize=9)
45
+ ax.set_ylim(0, 1)
46
+ ax.set_title(f'{SEGMENT_EMOJIS[cluster_id]} {cluster_names_loaded[cluster_id]}',
47
+ color='white', fontsize=11, fontweight='bold', pad=20)
48
+ ax.tick_params(colors='white')
49
+ ax.spines['polar'].set_color('#333')
50
+ ax.yaxis.set_tick_params(colors='#555')
51
+ ax.set_yticklabels([])
52
+ ax.grid(color='#333', linestyle='--', alpha=0.5)
53
+
54
+ plt.tight_layout()
55
+ return fig
56
+
57
+
58
+ def make_comparison_bar(user_vals, cluster_id):
59
+ """Bar chart: user values vs cluster centroid."""
60
+ centroid = scaler_loaded.inverse_transform(
61
+ kmeans_loaded.cluster_centers_[cluster_id].reshape(1, -1)
62
+ )[0]
63
+
64
+ features = ['Age', 'Annual Income (k$)', 'Spending Score']
65
+ x = np.arange(len(features))
66
+ width = 0.35
67
+
68
+ fig, ax = plt.subplots(figsize=(6, 3.5))
69
+ fig.patch.set_facecolor('#1a1a2e')
70
+ ax.set_facecolor('#16213e')
71
+
72
+ bars1 = ax.bar(x - width/2, user_vals, width, label='You',
73
+ color=SEGMENT_COLORS[cluster_id], alpha=0.9, edgecolor='white')
74
+ bars2 = ax.bar(x + width/2, centroid, width, label='Cluster Avg',
75
+ color='#aaaaaa', alpha=0.6, edgecolor='white')
76
+
77
+ ax.set_xticks(x)
78
+ ax.set_xticklabels(features, color='white', fontsize=9)
79
+ ax.set_ylabel('Value', color='white')
80
+ ax.set_title('You vs Cluster Average', color='white', fontweight='bold')
81
+ ax.tick_params(colors='white')
82
+ ax.spines[['top','right','left','bottom']].set_color('#333')
83
+ ax.yaxis.set_tick_params(colors='white')
84
+ ax.legend(facecolor='#222', labelcolor='white', fontsize=9)
85
+
86
+ for bar in bars1:
87
+ ax.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 0.5,
88
+ f'{bar.get_height():.0f}', ha='center', va='bottom',
89
+ color='white', fontsize=8)
90
+
91
+ plt.tight_layout()
92
+ return fig
93
+
94
+
95
+ def predict_segment(age, annual_income, spending_score):
96
+ """Core prediction function called by Gradio."""
97
+ user_input = np.array([[age, annual_income, spending_score]])
98
+ user_scaled = scaler_loaded.transform(user_input)
99
+ cluster_id = int(kmeans_loaded.predict(user_scaled)[0])
100
+
101
+ info = insights_loaded[cluster_id]
102
+ color = SEGMENT_COLORS[cluster_id]
103
+ emoji = SEGMENT_EMOJIS[cluster_id]
104
+
105
+ # Distance to all centroids
106
+ dists = kmeans_loaded.transform(user_scaled)[0]
107
+ confidence = 1 - (dists[cluster_id] / dists.sum())
108
+
109
+ result_html = f"""
110
+ <div style="background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
111
+ border-radius: 16px; padding: 24px; color: white; font-family: sans-serif;">
112
+ <div style="text-align:center; margin-bottom: 16px;">
113
+ <div style="font-size: 48px;">{emoji}</div>
114
+ <div style="font-size: 26px; font-weight: bold; color: {color};">
115
+ Cluster {cluster_id}: {cluster_names_loaded[cluster_id]}
116
+ </div>
117
+ <div style="font-size: 13px; color: #aaa; margin-top: 4px;">
118
+ Confidence: {confidence:.1%}
119
+ </div>
120
+ </div>
121
+ <hr style="border-color: #333; margin: 12px 0;">
122
+ <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px;">
123
+ <div style="background: #0f3460; border-radius: 10px; padding: 14px;">
124
+ <div style="font-size: 11px; color: #aaa; text-transform: uppercase; letter-spacing: 1px;">Profile</div>
125
+ <div style="margin-top: 6px; font-size: 14px;">{info['desc']}</div>
126
+ </div>
127
+ <div style="background: #0f3460; border-radius: 10px; padding: 14px;">
128
+ <div style="font-size: 11px; color: #aaa; text-transform: uppercase; letter-spacing: 1px;">🎯 Recommended Strategy</div>
129
+ <div style="margin-top: 6px; font-size: 14px; color: {color};">{info['strategy']}</div>
130
+ </div>
131
+ </div>
132
+ <div style="margin-top: 14px; background: #0f3460; border-radius: 10px; padding: 14px;">
133
+ <div style="font-size: 11px; color: #aaa; margin-bottom: 8px;">πŸ“ Distance to All Centroids (lower = closer)</div>
134
+ {''.join([
135
+ f'<div style="display:flex; align-items:center; margin-bottom:6px;">' +
136
+ f'<span style="width:120px; font-size:12px; color:{SEGMENT_COLORS[i]};">{cluster_names_loaded[i][:12]}</span>' +
137
+ f'<div style="flex:1; height:8px; background:#1a1a2e; border-radius:4px; overflow:hidden;">' +
138
+ f'<div style="height:8px; width:{min(100, dists[i]/max(dists)*100):.0f}%; background:{SEGMENT_COLORS[i]}; border-radius:4px;"></div>' +
139
+ f'</div><span style="margin-left:8px; font-size:12px; color:#aaa;">{dists[i]:.2f}</span></div>'
140
+ for i in range(K_OPTIMAL)
141
+ ])}
142
+ </div>
143
+ </div>
144
+ """
145
+
146
+ radar = make_radar_chart(cluster_id)
147
+ bar = make_comparison_bar([age, annual_income, spending_score], cluster_id)
148
+
149
+ return result_html, radar, bar
150
+
151
+
152
+ # ─── Gradio UI ───────────────────────────────────────────────────────────────
153
+ css = """
154
+ .gradio-container { max-width: 960px !important; margin: auto; font-family: 'Segoe UI', sans-serif; }
155
+ #title { text-align: center; margin-bottom: 20px; }
156
+ .input-panel { background: #16213e; border-radius: 12px; padding: 16px; }
157
+ """
158
+
159
+ EXAMPLES = [
160
+ [25, 80, 90],
161
+ [45, 30, 20],
162
+ [35, 60, 55],
163
+ [22, 15, 85],
164
+ [55, 90, 15],
165
+ ]
166
+
167
+ with gr.Blocks(css=css, theme=gr.themes.Base(primary_hue='blue'), title='Customer Segmentation') as demo:
168
+
169
+ gr.HTML("""
170
+ <div id="title">
171
+ <h1 style="font-size:2em; margin-bottom:4px;">πŸ›οΈ Customer Segmentation</h1>
172
+ <p style="color:#888;">K-Means Clustering Β· 5 Customer Segments Β· Real-time Prediction</p>
173
+ </div>
174
+ """)
175
+
176
+ with gr.Row():
177
+ with gr.Column(scale=1, elem_classes='input-panel'):
178
+ gr.Markdown('### πŸ“ Enter Customer Details')
179
+ age_inp = gr.Slider(18, 70, value=30, step=1, label='Age')
180
+ income_inp = gr.Slider(10, 140, value=60, step=1, label='Annual Income (k$)')
181
+ spend_inp = gr.Slider(1, 100, value=50, step=1, label='Spending Score (1–100)')
182
+ predict_btn = gr.Button('πŸ” Predict Segment', variant='primary', size='lg')
183
+
184
+ gr.Markdown('### πŸ’‘ Try Examples')
185
+ gr.Examples(
186
+ examples=EXAMPLES,
187
+ inputs=[age_inp, income_inp, spend_inp],
188
+ label='Quick Examples'
189
+ )
190
+
191
+ with gr.Column(scale=2):
192
+ result_html = gr.HTML(label='Segment Result')
193
+ with gr.Row():
194
+ radar_plot = gr.Plot(label='Cluster Radar Profile')
195
+ bar_plot = gr.Plot(label='You vs Cluster Average')
196
+
197
+ gr.Markdown("""
198
+ ---
199
+ **Segments:** ⚠️ Cautious Savers Β· πŸš€ High Potential Β· πŸ§‘β€πŸ’Ό Standard Customers Β· πŸ’° Budget Shoppers Β· πŸ‘‘ Premium Loyalists
200
+ **Model:** K-Means (K=5, k-means++ init) Β· Scaler: StandardScaler Β· Dataset: Mall Customers
201
+ """)
202
+
203
+ predict_btn.click(
204
+ fn=predict_segment,
205
+ inputs=[age_inp, income_inp, spend_inp],
206
+ outputs=[result_html, radar_plot, bar_plot]
207
+ )
208
+
209
+ # Launch
210
+ demo.launch(share=True, debug=False)