Akki2228 commited on
Commit
15dfebb
Β·
verified Β·
1 Parent(s): a5b3e42

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +267 -73
app.py CHANGED
@@ -35,42 +35,56 @@ def dashboard_analysis(age, gender, tenure, usage, support, delay,
35
  kpi = f"""
36
  ### πŸ“Š Customer Summary
37
  - Age: **{age}**
 
38
  - Tenure: **{tenure} months**
39
- - Spend: **β‚Ή{spend}**
40
- - Contract: **{contract}**
 
41
  - Subscription: **{subscription}**
 
 
 
42
  """
43
 
44
- # Chart 1: Profile
45
  fig1, ax1 = plt.subplots()
46
- features = ["Age","Tenure","Usage","Support","Delay"]
47
  values = [age, tenure, usage, support, delay]
 
48
  ax1.bar(features, values)
49
  ax1.set_title("Customer Profile")
50
  plt.close(fig1)
51
 
52
- # Chart 2: Financial
53
  fig2, ax2 = plt.subplots()
54
- ax2.bar(["Spend","Interaction"], [spend, interaction])
 
55
  ax2.set_title("Financial & Interaction")
56
  plt.close(fig2)
57
 
58
- # Chart 3: Risk indicators
59
  risk_scores = [
60
- delay/30,
61
- support/20,
62
- (6-tenure)/6 if tenure < 6 else 0
63
  ]
64
- labels = ["Delay Risk","Support Risk","Tenure Risk"]
 
65
 
66
  fig3, ax3 = plt.subplots()
67
  ax3.bar(labels, risk_scores)
68
  ax3.set_title("Risk Indicators")
69
  plt.close(fig3)
70
 
71
- # Chart 4: Subscription level
72
  fig4, ax4 = plt.subplots()
73
- sub_map = {"Basic":1, "Standard":2, "Premium":3}
 
 
 
 
 
 
74
  ax4.bar(["Subscription Level"], [sub_map[subscription]])
75
  ax4.set_title("Subscription Level")
76
  plt.close(fig4)
@@ -88,10 +102,11 @@ def predict_churn(age, gender, tenure, usage, support, delay,
88
  subscription, contract, spend, interaction):
89
 
90
  try:
 
91
  if model is None:
92
  return "Model not loaded ❌", "", "", None, ""
93
 
94
- # Convert inputs
95
  age = float(age)
96
  tenure = float(tenure)
97
  usage = float(usage)
@@ -102,18 +117,30 @@ def predict_churn(age, gender, tenure, usage, support, delay,
102
 
103
  # Encoding
104
  gender_val = 1 if gender == "Female" else 0
 
105
  sub_premium = 1 if subscription == "Premium" else 0
106
  sub_standard = 1 if subscription == "Standard" else 0
 
107
  contract_monthly = 1 if contract == "Monthly" else 0
108
  contract_quarterly = 1 if contract == "Quarterly" else 0
109
 
110
- input_data = np.array([[
111
- age, gender_val, tenure, usage, support, delay,
112
- spend, interaction,
113
- sub_premium, sub_standard,
114
- contract_monthly, contract_quarterly
 
 
 
 
 
 
 
 
 
115
  ]])
116
 
 
117
  pred = model.predict(input_data)[0]
118
 
119
  if hasattr(model, "predict_proba"):
@@ -121,8 +148,14 @@ def predict_churn(age, gender, tenure, usage, support, delay,
121
  else:
122
  prob = 0.5
123
 
124
- result = "⚠️ Likely to Churn" if pred == 1 else "βœ… Stable Customer"
 
 
 
 
 
125
 
 
126
  if prob > 0.7:
127
  risk = "πŸ”΄ High Risk"
128
  elif prob > 0.4:
@@ -130,22 +163,44 @@ def predict_churn(age, gender, tenure, usage, support, delay,
130
  else:
131
  risk = "🟒 Low Risk"
132
 
133
- # Probability chart
134
  fig, ax = plt.subplots()
135
- ax.bar(["No Churn","Churn"], [1-prob, prob])
136
- ax.set_ylim(0,1)
 
 
 
 
 
137
  ax.set_title("Prediction Probability")
 
138
  plt.close(fig)
139
 
140
  # Explanation
141
  reasons = []
142
- if delay > 15: reasons.append("High payment delay")
143
- if tenure < 6: reasons.append("Low tenure")
144
- if support > 5: reasons.append("Too many support calls")
145
 
146
- explanation = "\n".join(reasons) if reasons else "No strong risk indicators"
 
147
 
148
- return result, f"{prob*100:.2f}%", risk, fig, explanation
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
149
 
150
  except Exception as e:
151
  return f"Error: {str(e)}", "", "", None, ""
@@ -158,97 +213,236 @@ with gr.Blocks() as demo:
158
 
159
  gr.Markdown("# πŸš€ Customer Churn Interactive Dashboard")
160
 
161
- # ---------------------
162
  # πŸ“Š DASHBOARD TAB
163
- # ---------------------
164
  with gr.Tab("πŸ“Š Dashboard"):
165
 
166
  with gr.Row():
167
- d_age = gr.Number(value=30, label="Age")
168
- d_gender = gr.Dropdown(["Male","Female"], value="Male")
169
- d_tenure = gr.Number(value=12, label="Tenure")
170
- d_usage = gr.Number(value=10, label="Usage")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
171
 
172
  with gr.Row():
173
- d_support = gr.Number(value=2, label="Support Calls")
174
- d_delay = gr.Number(value=5, label="Payment Delay")
175
- d_subscription = gr.Dropdown(["Basic","Standard","Premium"], value="Basic")
176
- d_contract = gr.Dropdown(["Monthly","Quarterly","Yearly"], value="Monthly")
177
 
178
- d_spend = gr.Number(value=2000, label="Total Spend")
179
- d_interaction = gr.Number(value=20, label="Interaction")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
180
 
181
  analyze_btn = gr.Button("Analyze Dashboard")
182
 
183
  kpi_text = gr.Markdown()
184
- chart1 = gr.Plot()
185
- chart2 = gr.Plot()
186
- chart3 = gr.Plot()
187
- chart4 = gr.Plot()
 
188
 
189
  analyze_btn.click(
190
  dashboard_analysis,
191
- inputs=[d_age, d_gender, d_tenure, d_usage, d_support, d_delay,
192
- d_subscription, d_contract, d_spend, d_interaction],
193
- outputs=[kpi_text, chart1, chart2, chart3, chart4]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
194
  )
195
 
196
- # ---------------------
197
  # πŸ” PREDICTION TAB
198
- # ---------------------
199
  with gr.Tab("πŸ” Prediction"):
200
 
201
  with gr.Row():
202
- age = gr.Number(value=30, label="Age")
203
- gender = gr.Dropdown(["Male","Female"], value="Male")
204
- tenure = gr.Number(value=12, label="Tenure")
205
- usage = gr.Number(value=10, label="Usage")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
206
 
207
  with gr.Row():
208
- support = gr.Number(value=2, label="Support Calls")
209
- delay = gr.Number(value=5, label="Payment Delay")
210
- subscription = gr.Dropdown(["Basic","Standard","Premium"], value="Basic")
211
- contract = gr.Dropdown(["Monthly","Quarterly","Yearly"], value="Monthly")
212
 
213
- spend = gr.Number(value=2000, label="Total Spend")
214
- interaction = gr.Number(value=20, label="Interaction")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
215
 
216
  btn = gr.Button("Predict")
217
 
218
  result = gr.Textbox(label="Prediction")
219
  prob = gr.Textbox(label="Probability")
220
  risk = gr.Textbox(label="Risk Level")
221
- graph = gr.Plot()
222
- explanation = gr.Textbox(label="Why this prediction?")
 
 
223
 
224
  btn.click(
225
  predict_churn,
226
- inputs=[age, gender, tenure, usage, support, delay,
227
- subscription, contract, spend, interaction],
228
- outputs=[result, prob, risk, graph, explanation]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
229
  )
230
 
231
- # ---------------------
232
  # πŸ“ˆ INSIGHTS TAB
233
- # ---------------------
234
  with gr.Tab("πŸ“ˆ Insights"):
235
 
236
  if model is not None and hasattr(model, "feature_importances_"):
 
237
  fig, ax = plt.subplots()
 
238
  features = [
239
- "age","gender","tenure","usage","support","delay",
240
- "spend","interaction",
241
- "sub_premium","sub_standard",
242
- "contract_monthly","contract_quarterly"
 
 
 
 
 
 
 
 
243
  ]
244
- ax.barh(features, model.feature_importances_)
 
 
 
 
 
245
  ax.set_title("Feature Importance")
 
246
  plt.close(fig)
 
247
  gr.Plot(fig)
 
248
  else:
249
- gr.Markdown("⚠️ Feature importance not available")
 
 
250
 
251
  # =========================
252
- # πŸš€ LAUNCH
253
  # =========================
254
  demo.launch(debug=True)
 
35
  kpi = f"""
36
  ### πŸ“Š Customer Summary
37
  - Age: **{age}**
38
+ - Gender: **{gender}**
39
  - Tenure: **{tenure} months**
40
+ - Usage: **{usage}**
41
+ - Support Calls: **{support}**
42
+ - Payment Delay: **{delay}**
43
  - Subscription: **{subscription}**
44
+ - Contract Type: **{contract}**
45
+ - Total Spend: **β‚Ή{spend}**
46
+ - Interaction Score: **{interaction}**
47
  """
48
 
49
+ # Chart 1: Customer Profile
50
  fig1, ax1 = plt.subplots()
51
+ features = ["Age", "Tenure", "Usage", "Support", "Delay"]
52
  values = [age, tenure, usage, support, delay]
53
+
54
  ax1.bar(features, values)
55
  ax1.set_title("Customer Profile")
56
  plt.close(fig1)
57
 
58
+ # Chart 2: Financial & Interaction
59
  fig2, ax2 = plt.subplots()
60
+
61
+ ax2.bar(["Spend", "Interaction"], [spend, interaction])
62
  ax2.set_title("Financial & Interaction")
63
  plt.close(fig2)
64
 
65
+ # Chart 3: Risk Indicators
66
  risk_scores = [
67
+ delay / 30,
68
+ support / 20,
69
+ (6 - tenure) / 6 if tenure < 6 else 0
70
  ]
71
+
72
+ labels = ["Delay Risk", "Support Risk", "Tenure Risk"]
73
 
74
  fig3, ax3 = plt.subplots()
75
  ax3.bar(labels, risk_scores)
76
  ax3.set_title("Risk Indicators")
77
  plt.close(fig3)
78
 
79
+ # Chart 4: Subscription Level
80
  fig4, ax4 = plt.subplots()
81
+
82
+ sub_map = {
83
+ "Basic": 1,
84
+ "Standard": 2,
85
+ "Premium": 3
86
+ }
87
+
88
  ax4.bar(["Subscription Level"], [sub_map[subscription]])
89
  ax4.set_title("Subscription Level")
90
  plt.close(fig4)
 
102
  subscription, contract, spend, interaction):
103
 
104
  try:
105
+
106
  if model is None:
107
  return "Model not loaded ❌", "", "", None, ""
108
 
109
+ # Convert Inputs
110
  age = float(age)
111
  tenure = float(tenure)
112
  usage = float(usage)
 
117
 
118
  # Encoding
119
  gender_val = 1 if gender == "Female" else 0
120
+
121
  sub_premium = 1 if subscription == "Premium" else 0
122
  sub_standard = 1 if subscription == "Standard" else 0
123
+
124
  contract_monthly = 1 if contract == "Monthly" else 0
125
  contract_quarterly = 1 if contract == "Quarterly" else 0
126
 
127
+ # Model Input
128
+ input_data = np.array([[
129
+ age,
130
+ gender_val,
131
+ tenure,
132
+ usage,
133
+ support,
134
+ delay,
135
+ spend,
136
+ interaction,
137
+ sub_premium,
138
+ sub_standard,
139
+ contract_monthly,
140
+ contract_quarterly
141
  ]])
142
 
143
+ # Prediction
144
  pred = model.predict(input_data)[0]
145
 
146
  if hasattr(model, "predict_proba"):
 
148
  else:
149
  prob = 0.5
150
 
151
+ # Result
152
+ result = (
153
+ "⚠️ Likely to Churn"
154
+ if pred == 1
155
+ else "βœ… Stable Customer"
156
+ )
157
 
158
+ # Risk Level
159
  if prob > 0.7:
160
  risk = "πŸ”΄ High Risk"
161
  elif prob > 0.4:
 
163
  else:
164
  risk = "🟒 Low Risk"
165
 
166
+ # Probability Chart
167
  fig, ax = plt.subplots()
168
+
169
+ ax.bar(
170
+ ["No Churn", "Churn"],
171
+ [1 - prob, prob]
172
+ )
173
+
174
+ ax.set_ylim(0, 1)
175
  ax.set_title("Prediction Probability")
176
+
177
  plt.close(fig)
178
 
179
  # Explanation
180
  reasons = []
 
 
 
181
 
182
+ if delay > 15:
183
+ reasons.append("High payment delay")
184
 
185
+ if tenure < 6:
186
+ reasons.append("Low tenure")
187
+
188
+ if support > 5:
189
+ reasons.append("Too many support calls")
190
+
191
+ explanation = (
192
+ "\n".join(reasons)
193
+ if reasons
194
+ else "No strong risk indicators"
195
+ )
196
+
197
+ return (
198
+ result,
199
+ f"{prob * 100:.2f}%",
200
+ risk,
201
+ fig,
202
+ explanation
203
+ )
204
 
205
  except Exception as e:
206
  return f"Error: {str(e)}", "", "", None, ""
 
213
 
214
  gr.Markdown("# πŸš€ Customer Churn Interactive Dashboard")
215
 
216
+ # =====================================================
217
  # πŸ“Š DASHBOARD TAB
218
+ # =====================================================
219
  with gr.Tab("πŸ“Š Dashboard"):
220
 
221
  with gr.Row():
222
+
223
+ d_age = gr.Number(
224
+ value=30,
225
+ label="Age"
226
+ )
227
+
228
+ d_gender = gr.Dropdown(
229
+ ["Male", "Female"],
230
+ value="Male",
231
+ label="Gender"
232
+ )
233
+
234
+ d_tenure = gr.Number(
235
+ value=12,
236
+ label="Tenure"
237
+ )
238
+
239
+ d_usage = gr.Number(
240
+ value=10,
241
+ label="Usage"
242
+ )
243
 
244
  with gr.Row():
 
 
 
 
245
 
246
+ d_support = gr.Number(
247
+ value=2,
248
+ label="Support Calls"
249
+ )
250
+
251
+ d_delay = gr.Number(
252
+ value=5,
253
+ label="Payment Delay"
254
+ )
255
+
256
+ d_subscription = gr.Dropdown(
257
+ ["Basic", "Standard", "Premium"],
258
+ value="Basic",
259
+ label="Subscription"
260
+ )
261
+
262
+ d_contract = gr.Dropdown(
263
+ ["Monthly", "Quarterly", "Yearly"],
264
+ value="Monthly",
265
+ label="Contract Type"
266
+ )
267
+
268
+ d_spend = gr.Number(
269
+ value=2000,
270
+ label="Total Spend"
271
+ )
272
+
273
+ d_interaction = gr.Number(
274
+ value=20,
275
+ label="Interaction"
276
+ )
277
 
278
  analyze_btn = gr.Button("Analyze Dashboard")
279
 
280
  kpi_text = gr.Markdown()
281
+
282
+ chart1 = gr.Plot(label="Customer Profile")
283
+ chart2 = gr.Plot(label="Financial Analysis")
284
+ chart3 = gr.Plot(label="Risk Indicators")
285
+ chart4 = gr.Plot(label="Subscription Analysis")
286
 
287
  analyze_btn.click(
288
  dashboard_analysis,
289
+ inputs=[
290
+ d_age,
291
+ d_gender,
292
+ d_tenure,
293
+ d_usage,
294
+ d_support,
295
+ d_delay,
296
+ d_subscription,
297
+ d_contract,
298
+ d_spend,
299
+ d_interaction
300
+ ],
301
+ outputs=[
302
+ kpi_text,
303
+ chart1,
304
+ chart2,
305
+ chart3,
306
+ chart4
307
+ ]
308
  )
309
 
310
+ # =====================================================
311
  # πŸ” PREDICTION TAB
312
+ # =====================================================
313
  with gr.Tab("πŸ” Prediction"):
314
 
315
  with gr.Row():
316
+
317
+ age = gr.Number(
318
+ value=30,
319
+ label="Age"
320
+ )
321
+
322
+ gender = gr.Dropdown(
323
+ ["Male", "Female"],
324
+ value="Male",
325
+ label="Gender"
326
+ )
327
+
328
+ tenure = gr.Number(
329
+ value=12,
330
+ label="Tenure"
331
+ )
332
+
333
+ usage = gr.Number(
334
+ value=10,
335
+ label="Usage"
336
+ )
337
 
338
  with gr.Row():
 
 
 
 
339
 
340
+ support = gr.Number(
341
+ value=2,
342
+ label="Support Calls"
343
+ )
344
+
345
+ delay = gr.Number(
346
+ value=5,
347
+ label="Payment Delay"
348
+ )
349
+
350
+ subscription = gr.Dropdown(
351
+ ["Basic", "Standard", "Premium"],
352
+ value="Basic",
353
+ label="Subscription"
354
+ )
355
+
356
+ contract = gr.Dropdown(
357
+ ["Monthly", "Quarterly", "Yearly"],
358
+ value="Monthly",
359
+ label="Contract Type"
360
+ )
361
+
362
+ spend = gr.Number(
363
+ value=2000,
364
+ label="Total Spend"
365
+ )
366
+
367
+ interaction = gr.Number(
368
+ value=20,
369
+ label="Interaction"
370
+ )
371
 
372
  btn = gr.Button("Predict")
373
 
374
  result = gr.Textbox(label="Prediction")
375
  prob = gr.Textbox(label="Probability")
376
  risk = gr.Textbox(label="Risk Level")
377
+ graph = gr.Plot(label="Prediction Graph")
378
+ explanation = gr.Textbox(
379
+ label="Why this prediction?"
380
+ )
381
 
382
  btn.click(
383
  predict_churn,
384
+ inputs=[
385
+ age,
386
+ gender,
387
+ tenure,
388
+ usage,
389
+ support,
390
+ delay,
391
+ subscription,
392
+ contract,
393
+ spend,
394
+ interaction
395
+ ],
396
+ outputs=[
397
+ result,
398
+ prob,
399
+ risk,
400
+ graph,
401
+ explanation
402
+ ]
403
  )
404
 
405
+ # =====================================================
406
  # πŸ“ˆ INSIGHTS TAB
407
+ # =====================================================
408
  with gr.Tab("πŸ“ˆ Insights"):
409
 
410
  if model is not None and hasattr(model, "feature_importances_"):
411
+
412
  fig, ax = plt.subplots()
413
+
414
  features = [
415
+ "Age",
416
+ "Gender",
417
+ "Tenure",
418
+ "Usage",
419
+ "Support",
420
+ "Delay",
421
+ "Spend",
422
+ "Interaction",
423
+ "Premium Subscription",
424
+ "Standard Subscription",
425
+ "Monthly Contract",
426
+ "Quarterly Contract"
427
  ]
428
+
429
+ ax.barh(
430
+ features,
431
+ model.feature_importances_
432
+ )
433
+
434
  ax.set_title("Feature Importance")
435
+
436
  plt.close(fig)
437
+
438
  gr.Plot(fig)
439
+
440
  else:
441
+ gr.Markdown(
442
+ "⚠️ Feature importance not available"
443
+ )
444
 
445
  # =========================
446
+ # πŸš€ Launch App
447
  # =========================
448
  demo.launch(debug=True)