Customer_Churn / app.py
Akki2228's picture
Update app.py
15dfebb verified
Raw
History Blame Contribute Delete
10.9 kB
import gradio as gr
import pickle
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
matplotlib.use("Agg")
# =========================
# πŸ”Ή Load Model
# =========================
try:
with open("DecisionTreeClassifier.pkl", "rb") as f:
model = pickle.load(f)
except:
model = None
# =========================
# πŸ”Ή DASHBOARD ANALYSIS
# =========================
def dashboard_analysis(age, gender, tenure, usage, support, delay,
subscription, contract, spend, interaction):
try:
# Convert inputs
age = float(age)
tenure = float(tenure)
usage = float(usage)
support = float(support)
delay = float(delay)
spend = float(spend)
interaction = float(interaction)
# KPI Summary
kpi = f"""
### πŸ“Š Customer Summary
- Age: **{age}**
- Gender: **{gender}**
- Tenure: **{tenure} months**
- Usage: **{usage}**
- Support Calls: **{support}**
- Payment Delay: **{delay}**
- Subscription: **{subscription}**
- Contract Type: **{contract}**
- Total Spend: **β‚Ή{spend}**
- Interaction Score: **{interaction}**
"""
# Chart 1: Customer Profile
fig1, ax1 = plt.subplots()
features = ["Age", "Tenure", "Usage", "Support", "Delay"]
values = [age, tenure, usage, support, delay]
ax1.bar(features, values)
ax1.set_title("Customer Profile")
plt.close(fig1)
# Chart 2: Financial & Interaction
fig2, ax2 = plt.subplots()
ax2.bar(["Spend", "Interaction"], [spend, interaction])
ax2.set_title("Financial & Interaction")
plt.close(fig2)
# Chart 3: Risk Indicators
risk_scores = [
delay / 30,
support / 20,
(6 - tenure) / 6 if tenure < 6 else 0
]
labels = ["Delay Risk", "Support Risk", "Tenure Risk"]
fig3, ax3 = plt.subplots()
ax3.bar(labels, risk_scores)
ax3.set_title("Risk Indicators")
plt.close(fig3)
# Chart 4: Subscription Level
fig4, ax4 = plt.subplots()
sub_map = {
"Basic": 1,
"Standard": 2,
"Premium": 3
}
ax4.bar(["Subscription Level"], [sub_map[subscription]])
ax4.set_title("Subscription Level")
plt.close(fig4)
return kpi, fig1, fig2, fig3, fig4
except Exception as e:
return f"Error: {str(e)}", None, None, None, None
# =========================
# πŸ”Ή PREDICTION FUNCTION
# =========================
def predict_churn(age, gender, tenure, usage, support, delay,
subscription, contract, spend, interaction):
try:
if model is None:
return "Model not loaded ❌", "", "", None, ""
# Convert Inputs
age = float(age)
tenure = float(tenure)
usage = float(usage)
support = float(support)
delay = float(delay)
spend = float(spend)
interaction = float(interaction)
# Encoding
gender_val = 1 if gender == "Female" else 0
sub_premium = 1 if subscription == "Premium" else 0
sub_standard = 1 if subscription == "Standard" else 0
contract_monthly = 1 if contract == "Monthly" else 0
contract_quarterly = 1 if contract == "Quarterly" else 0
# Model Input
input_data = np.array([[
age,
gender_val,
tenure,
usage,
support,
delay,
spend,
interaction,
sub_premium,
sub_standard,
contract_monthly,
contract_quarterly
]])
# Prediction
pred = model.predict(input_data)[0]
if hasattr(model, "predict_proba"):
prob = model.predict_proba(input_data)[0][1]
else:
prob = 0.5
# Result
result = (
"⚠️ Likely to Churn"
if pred == 1
else "βœ… Stable Customer"
)
# Risk Level
if prob > 0.7:
risk = "πŸ”΄ High Risk"
elif prob > 0.4:
risk = "🟠 Medium Risk"
else:
risk = "🟒 Low Risk"
# Probability Chart
fig, ax = plt.subplots()
ax.bar(
["No Churn", "Churn"],
[1 - prob, prob]
)
ax.set_ylim(0, 1)
ax.set_title("Prediction Probability")
plt.close(fig)
# Explanation
reasons = []
if delay > 15:
reasons.append("High payment delay")
if tenure < 6:
reasons.append("Low tenure")
if support > 5:
reasons.append("Too many support calls")
explanation = (
"\n".join(reasons)
if reasons
else "No strong risk indicators"
)
return (
result,
f"{prob * 100:.2f}%",
risk,
fig,
explanation
)
except Exception as e:
return f"Error: {str(e)}", "", "", None, ""
# =========================
# 🎨 UI
# =========================
with gr.Blocks() as demo:
gr.Markdown("# πŸš€ Customer Churn Interactive Dashboard")
# =====================================================
# πŸ“Š DASHBOARD TAB
# =====================================================
with gr.Tab("πŸ“Š Dashboard"):
with gr.Row():
d_age = gr.Number(
value=30,
label="Age"
)
d_gender = gr.Dropdown(
["Male", "Female"],
value="Male",
label="Gender"
)
d_tenure = gr.Number(
value=12,
label="Tenure"
)
d_usage = gr.Number(
value=10,
label="Usage"
)
with gr.Row():
d_support = gr.Number(
value=2,
label="Support Calls"
)
d_delay = gr.Number(
value=5,
label="Payment Delay"
)
d_subscription = gr.Dropdown(
["Basic", "Standard", "Premium"],
value="Basic",
label="Subscription"
)
d_contract = gr.Dropdown(
["Monthly", "Quarterly", "Yearly"],
value="Monthly",
label="Contract Type"
)
d_spend = gr.Number(
value=2000,
label="Total Spend"
)
d_interaction = gr.Number(
value=20,
label="Interaction"
)
analyze_btn = gr.Button("Analyze Dashboard")
kpi_text = gr.Markdown()
chart1 = gr.Plot(label="Customer Profile")
chart2 = gr.Plot(label="Financial Analysis")
chart3 = gr.Plot(label="Risk Indicators")
chart4 = gr.Plot(label="Subscription Analysis")
analyze_btn.click(
dashboard_analysis,
inputs=[
d_age,
d_gender,
d_tenure,
d_usage,
d_support,
d_delay,
d_subscription,
d_contract,
d_spend,
d_interaction
],
outputs=[
kpi_text,
chart1,
chart2,
chart3,
chart4
]
)
# =====================================================
# πŸ” PREDICTION TAB
# =====================================================
with gr.Tab("πŸ” Prediction"):
with gr.Row():
age = gr.Number(
value=30,
label="Age"
)
gender = gr.Dropdown(
["Male", "Female"],
value="Male",
label="Gender"
)
tenure = gr.Number(
value=12,
label="Tenure"
)
usage = gr.Number(
value=10,
label="Usage"
)
with gr.Row():
support = gr.Number(
value=2,
label="Support Calls"
)
delay = gr.Number(
value=5,
label="Payment Delay"
)
subscription = gr.Dropdown(
["Basic", "Standard", "Premium"],
value="Basic",
label="Subscription"
)
contract = gr.Dropdown(
["Monthly", "Quarterly", "Yearly"],
value="Monthly",
label="Contract Type"
)
spend = gr.Number(
value=2000,
label="Total Spend"
)
interaction = gr.Number(
value=20,
label="Interaction"
)
btn = gr.Button("Predict")
result = gr.Textbox(label="Prediction")
prob = gr.Textbox(label="Probability")
risk = gr.Textbox(label="Risk Level")
graph = gr.Plot(label="Prediction Graph")
explanation = gr.Textbox(
label="Why this prediction?"
)
btn.click(
predict_churn,
inputs=[
age,
gender,
tenure,
usage,
support,
delay,
subscription,
contract,
spend,
interaction
],
outputs=[
result,
prob,
risk,
graph,
explanation
]
)
# =====================================================
# πŸ“ˆ INSIGHTS TAB
# =====================================================
with gr.Tab("πŸ“ˆ Insights"):
if model is not None and hasattr(model, "feature_importances_"):
fig, ax = plt.subplots()
features = [
"Age",
"Gender",
"Tenure",
"Usage",
"Support",
"Delay",
"Spend",
"Interaction",
"Premium Subscription",
"Standard Subscription",
"Monthly Contract",
"Quarterly Contract"
]
ax.barh(
features,
model.feature_importances_
)
ax.set_title("Feature Importance")
plt.close(fig)
gr.Plot(fig)
else:
gr.Markdown(
"⚠️ Feature importance not available"
)
# =========================
# πŸš€ Launch App
# =========================
demo.launch(debug=True)