Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,15 +1,130 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
import pickle
|
| 3 |
import numpy as np
|
|
|
|
| 4 |
import matplotlib.pyplot as plt
|
|
|
|
|
|
|
| 5 |
|
| 6 |
-
#
|
| 7 |
-
|
| 8 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
def predict_churn(age, gender, tenure, usage, support, delay,
|
| 11 |
-
|
|
|
|
| 12 |
try:
|
|
|
|
|
|
|
|
|
|
| 13 |
gender_val = 1 if gender == "Female" else 0
|
| 14 |
|
| 15 |
sub_premium = 1 if subscription == "Premium" else 0
|
|
@@ -26,11 +141,14 @@ def predict_churn(age, gender, tenure, usage, support, delay,
|
|
| 26 |
]])
|
| 27 |
|
| 28 |
pred = model.predict(input_data)[0]
|
| 29 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
|
| 31 |
result = "β οΈ Likely to Churn" if pred == 1 else "β
Stable Customer"
|
| 32 |
|
| 33 |
-
# Risk label
|
| 34 |
if prob > 0.7:
|
| 35 |
risk = "π΄ High Risk"
|
| 36 |
elif prob > 0.4:
|
|
@@ -38,61 +156,110 @@ def predict_churn(age, gender, tenure, usage, support, delay,
|
|
| 38 |
else:
|
| 39 |
risk = "π’ Low Risk"
|
| 40 |
|
| 41 |
-
#
|
| 42 |
fig, ax = plt.subplots()
|
| 43 |
-
ax.bar(["No Churn",
|
| 44 |
-
ax.
|
| 45 |
-
ax.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
|
| 47 |
-
return result, f"{prob*100:.2f}%", risk, fig
|
| 48 |
|
| 49 |
except Exception as e:
|
| 50 |
-
return f"Error: {str(e)}", "", "", None
|
| 51 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
|
| 53 |
-
#
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
|
| 60 |
-
#
|
| 61 |
-
|
|
|
|
| 62 |
|
| 63 |
-
|
| 64 |
-
|
|
|
|
|
|
|
| 65 |
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
usage = gr.Slider(0, 50, label="Usage Frequency")
|
| 72 |
|
| 73 |
-
with gr.
|
| 74 |
-
support = gr.Slider(0,
|
| 75 |
-
delay = gr.Slider(0,
|
| 76 |
-
subscription = gr.Radio(["Basic",
|
| 77 |
-
contract = gr.Radio(["Monthly",
|
| 78 |
|
| 79 |
-
|
| 80 |
-
|
| 81 |
|
| 82 |
-
|
| 83 |
|
| 84 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 85 |
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
|
|
|
|
|
|
| 90 |
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
|
| 98 |
-
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
import pickle
|
| 3 |
import numpy as np
|
| 4 |
+
import pandas as pd
|
| 5 |
import matplotlib.pyplot as plt
|
| 6 |
+
import matplotlib
|
| 7 |
+
matplotlib.use("Agg")
|
| 8 |
|
| 9 |
+
# =========================
|
| 10 |
+
# πΉ Load Model
|
| 11 |
+
# =========================
|
| 12 |
+
try:
|
| 13 |
+
with open("DecisionTreeClassifier.pkl", "rb") as f:
|
| 14 |
+
model = pickle.load(f)
|
| 15 |
+
except:
|
| 16 |
+
model = None
|
| 17 |
|
| 18 |
+
# =========================
|
| 19 |
+
# πΉ Load Dataset (REAL or DUMMY)
|
| 20 |
+
# =========================
|
| 21 |
+
try:
|
| 22 |
+
data = pd.read_csv("churn_data.csv") # π₯ Replace with your dataset
|
| 23 |
+
except:
|
| 24 |
+
# fallback dummy dataset
|
| 25 |
+
np.random.seed(42)
|
| 26 |
+
data = pd.DataFrame({
|
| 27 |
+
"gender": np.random.choice(["Male","Female"], 300),
|
| 28 |
+
"tenure": np.random.randint(1, 60, 300),
|
| 29 |
+
"MonthlyCharges": np.random.randint(500, 8000, 300),
|
| 30 |
+
"Contract": np.random.choice(["Monthly","Quarterly","Yearly"], 300),
|
| 31 |
+
"Churn": np.random.choice([0,1], 300)
|
| 32 |
+
})
|
| 33 |
+
|
| 34 |
+
# =========================
|
| 35 |
+
# πΉ KPI FUNCTION
|
| 36 |
+
# =========================
|
| 37 |
+
def get_kpis(df):
|
| 38 |
+
total = len(df)
|
| 39 |
+
churn_rate = df["Churn"].mean() * 100
|
| 40 |
+
avg_spend = df["MonthlyCharges"].mean()
|
| 41 |
+
avg_tenure = df["tenure"].mean()
|
| 42 |
+
|
| 43 |
+
return f"""
|
| 44 |
+
### π Key Metrics
|
| 45 |
+
- Total Customers: **{total}**
|
| 46 |
+
- Churn Rate: **{churn_rate:.2f}%**
|
| 47 |
+
- Avg Spend: **βΉ{avg_spend:.0f}**
|
| 48 |
+
- Avg Tenure: **{avg_tenure:.1f} months**
|
| 49 |
+
"""
|
| 50 |
+
|
| 51 |
+
# =========================
|
| 52 |
+
# πΉ FILTER FUNCTION
|
| 53 |
+
# =========================
|
| 54 |
+
def apply_filters(gender, contract):
|
| 55 |
+
df = data.copy()
|
| 56 |
+
|
| 57 |
+
if gender != "All":
|
| 58 |
+
df = df[df["gender"] == gender]
|
| 59 |
+
|
| 60 |
+
if contract != "All":
|
| 61 |
+
df = df[df["Contract"] == contract]
|
| 62 |
+
|
| 63 |
+
return df
|
| 64 |
+
|
| 65 |
+
# =========================
|
| 66 |
+
# πΉ CHARTS
|
| 67 |
+
# =========================
|
| 68 |
+
def churn_dist(df):
|
| 69 |
+
fig, ax = plt.subplots()
|
| 70 |
+
counts = df["Churn"].value_counts()
|
| 71 |
+
ax.bar(["No Churn","Churn"], counts)
|
| 72 |
+
ax.set_title("Churn Distribution")
|
| 73 |
+
plt.close(fig)
|
| 74 |
+
return fig
|
| 75 |
+
|
| 76 |
+
def contract_chart(df):
|
| 77 |
+
fig, ax = plt.subplots()
|
| 78 |
+
pd.crosstab(df["Contract"], df["Churn"]).plot(kind="bar", ax=ax)
|
| 79 |
+
ax.set_title("Churn by Contract")
|
| 80 |
+
plt.close(fig)
|
| 81 |
+
return fig
|
| 82 |
+
|
| 83 |
+
def tenure_chart(df):
|
| 84 |
+
fig, ax = plt.subplots()
|
| 85 |
+
ax.scatter(df["tenure"], df["Churn"])
|
| 86 |
+
ax.set_title("Tenure vs Churn")
|
| 87 |
+
plt.close(fig)
|
| 88 |
+
return fig
|
| 89 |
+
|
| 90 |
+
def risk_pie(df):
|
| 91 |
+
fig, ax = plt.subplots()
|
| 92 |
+
counts = df["Churn"].value_counts()
|
| 93 |
+
ax.pie(counts, labels=["No Churn","Churn"], autopct="%1.1f%%")
|
| 94 |
+
ax.set_title("Risk Segmentation")
|
| 95 |
+
plt.close(fig)
|
| 96 |
+
return fig
|
| 97 |
+
|
| 98 |
+
# =========================
|
| 99 |
+
# πΉ FEATURE IMPORTANCE
|
| 100 |
+
# =========================
|
| 101 |
+
def feature_importance():
|
| 102 |
+
if model is None or not hasattr(model, "feature_importances_"):
|
| 103 |
+
return None
|
| 104 |
+
|
| 105 |
+
features = [
|
| 106 |
+
"age","gender","tenure","usage","support","delay",
|
| 107 |
+
"spend","interaction",
|
| 108 |
+
"sub_premium","sub_standard",
|
| 109 |
+
"contract_monthly","contract_quarterly"
|
| 110 |
+
]
|
| 111 |
+
|
| 112 |
+
fig, ax = plt.subplots()
|
| 113 |
+
ax.barh(features, model.feature_importances_)
|
| 114 |
+
ax.set_title("Feature Importance")
|
| 115 |
+
plt.close(fig)
|
| 116 |
+
return fig
|
| 117 |
+
|
| 118 |
+
# =========================
|
| 119 |
+
# πΉ PREDICTION
|
| 120 |
+
# =========================
|
| 121 |
def predict_churn(age, gender, tenure, usage, support, delay,
|
| 122 |
+
subscription, contract, spend, interaction):
|
| 123 |
+
|
| 124 |
try:
|
| 125 |
+
if model is None:
|
| 126 |
+
return "Model not loaded β", "", "", None, ""
|
| 127 |
+
|
| 128 |
gender_val = 1 if gender == "Female" else 0
|
| 129 |
|
| 130 |
sub_premium = 1 if subscription == "Premium" else 0
|
|
|
|
| 141 |
]])
|
| 142 |
|
| 143 |
pred = model.predict(input_data)[0]
|
| 144 |
+
|
| 145 |
+
if hasattr(model, "predict_proba"):
|
| 146 |
+
prob = model.predict_proba(input_data)[0][1]
|
| 147 |
+
else:
|
| 148 |
+
prob = 0.5
|
| 149 |
|
| 150 |
result = "β οΈ Likely to Churn" if pred == 1 else "β
Stable Customer"
|
| 151 |
|
|
|
|
| 152 |
if prob > 0.7:
|
| 153 |
risk = "π΄ High Risk"
|
| 154 |
elif prob > 0.4:
|
|
|
|
| 156 |
else:
|
| 157 |
risk = "π’ Low Risk"
|
| 158 |
|
| 159 |
+
# probability chart
|
| 160 |
fig, ax = plt.subplots()
|
| 161 |
+
ax.bar(["No Churn","Churn"], [1-prob, prob])
|
| 162 |
+
ax.set_ylim(0,1)
|
| 163 |
+
ax.set_title("Prediction Probability")
|
| 164 |
+
plt.close(fig)
|
| 165 |
+
|
| 166 |
+
# explanation
|
| 167 |
+
reasons = []
|
| 168 |
+
if delay > 15: reasons.append("High payment delay")
|
| 169 |
+
if tenure < 6: reasons.append("Low tenure")
|
| 170 |
+
if support > 5: reasons.append("Too many support calls")
|
| 171 |
+
|
| 172 |
+
explanation = "\n".join(reasons) if reasons else "No strong risk indicators"
|
| 173 |
|
| 174 |
+
return result, f"{prob*100:.2f}%", risk, fig, explanation
|
| 175 |
|
| 176 |
except Exception as e:
|
| 177 |
+
return f"Error: {str(e)}", "", "", None, ""
|
| 178 |
|
| 179 |
+
# =========================
|
| 180 |
+
# π¨ UI
|
| 181 |
+
# =========================
|
| 182 |
+
with gr.Blocks() as demo:
|
| 183 |
|
| 184 |
+
gr.Markdown("# π Customer Churn Analytics Dashboard")
|
| 185 |
+
|
| 186 |
+
# ---------------------
|
| 187 |
+
# π DASHBOARD TAB
|
| 188 |
+
# ---------------------
|
| 189 |
+
with gr.Tab("π Dashboard"):
|
| 190 |
+
|
| 191 |
+
gender_filter = gr.Dropdown(["All","Male","Female"], value="All", label="Filter by Gender")
|
| 192 |
+
contract_filter = gr.Dropdown(["All","Monthly","Quarterly","Yearly"], value="All", label="Filter by Contract")
|
| 193 |
+
|
| 194 |
+
kpi_text = gr.Markdown()
|
| 195 |
+
chart1 = gr.Plot()
|
| 196 |
+
chart2 = gr.Plot()
|
| 197 |
+
chart3 = gr.Plot()
|
| 198 |
+
chart4 = gr.Plot()
|
| 199 |
+
|
| 200 |
+
def update_dashboard(g, c):
|
| 201 |
+
df = apply_filters(g, c)
|
| 202 |
+
return (
|
| 203 |
+
get_kpis(df),
|
| 204 |
+
churn_dist(df),
|
| 205 |
+
contract_chart(df),
|
| 206 |
+
tenure_chart(df),
|
| 207 |
+
risk_pie(df)
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
gender_filter.change(update_dashboard, [gender_filter, contract_filter],
|
| 211 |
+
[kpi_text, chart1, chart2, chart3, chart4])
|
| 212 |
+
|
| 213 |
+
contract_filter.change(update_dashboard, [gender_filter, contract_filter],
|
| 214 |
+
[kpi_text, chart1, chart2, chart3, chart4])
|
| 215 |
|
| 216 |
+
# initial load
|
| 217 |
+
demo.load(update_dashboard, [gender_filter, contract_filter],
|
| 218 |
+
[kpi_text, chart1, chart2, chart3, chart4])
|
| 219 |
|
| 220 |
+
# ---------------------
|
| 221 |
+
# π PREDICTION TAB
|
| 222 |
+
# ---------------------
|
| 223 |
+
with gr.Tab("π Prediction"):
|
| 224 |
|
| 225 |
+
with gr.Row():
|
| 226 |
+
age = gr.Slider(18,80,value=30)
|
| 227 |
+
gender = gr.Radio(["Male","Female"], value="Male")
|
| 228 |
+
tenure = gr.Slider(0,60,value=12)
|
| 229 |
+
usage = gr.Slider(0,50,value=10)
|
|
|
|
| 230 |
|
| 231 |
+
with gr.Row():
|
| 232 |
+
support = gr.Slider(0,20,value=2)
|
| 233 |
+
delay = gr.Slider(0,30,value=5)
|
| 234 |
+
subscription = gr.Radio(["Basic","Standard","Premium"], value="Basic")
|
| 235 |
+
contract = gr.Radio(["Monthly","Quarterly","Yearly"], value="Monthly")
|
| 236 |
|
| 237 |
+
spend = gr.Slider(0,10000,value=2000)
|
| 238 |
+
interaction = gr.Slider(0,100,value=20)
|
| 239 |
|
| 240 |
+
btn = gr.Button("Predict")
|
| 241 |
|
| 242 |
+
result = gr.Textbox(label="Prediction")
|
| 243 |
+
prob = gr.Textbox(label="Probability")
|
| 244 |
+
risk = gr.Textbox(label="Risk Level")
|
| 245 |
+
graph = gr.Plot()
|
| 246 |
+
explanation = gr.Textbox(label="Why this prediction?")
|
| 247 |
|
| 248 |
+
btn.click(
|
| 249 |
+
predict_churn,
|
| 250 |
+
inputs=[age, gender, tenure, usage, support, delay,
|
| 251 |
+
subscription, contract, spend, interaction],
|
| 252 |
+
outputs=[result, prob, risk, graph, explanation]
|
| 253 |
+
)
|
| 254 |
|
| 255 |
+
# ---------------------
|
| 256 |
+
# π INSIGHTS TAB
|
| 257 |
+
# ---------------------
|
| 258 |
+
with gr.Tab("π Insights"):
|
| 259 |
+
gr.Markdown("### Feature Importance")
|
| 260 |
+
gr.Plot(feature_importance())
|
| 261 |
|
| 262 |
+
# =========================
|
| 263 |
+
# π LAUNCH
|
| 264 |
+
# =========================
|
| 265 |
+
demo.launch(debug=True)
|