ghinaAI/Telecom_Customer_Churn_Prediction
0
1import joblib2import pandas as pd3import gradio as gr4 5# Load model6model = joblib.load("best_xgb_model.pkl")7 8# Expected features9expected_columns = [10 'SeniorCitizen', 'Partner', 'Dependents', 'PhoneService', 'MultipleLines',11 'OnlineSecurity', 'OnlineBackup', 'DeviceProtection', 'TechSupport', 'StreamingTV',12 'StreamingMovies', 'PaperlessBilling', 'MonthlyCharges', 'TotalCharges',13 'PaymentMethod_Credit card (automatic)', 'PaymentMethod_Electronic check',14 'PaymentMethod_Mailed check', 'InternetService_Fiber optic', 'InternetService_No',15 'Contract_One year', 'Contract_Two year',16 'TenureGroup_Experienced', 'TenureGroup_Loyal'17]18 19# Suggestion generator20def generate_suggestion(customer):21 suggestions = []22 23 if customer["Contract_One year"] == 0 and customer["Contract_Two year"] == 0:24 suggestions.append("Offer a yearly plan with 2 months free.")25 if customer["MonthlyCharges"] > 80:26 suggestions.append("Propose a discounted or lower-cost plan.")27 if customer["TechSupport"] == 0:28 suggestions.append("Provide 3 months of free tech support.")29 if customer["OnlineSecurity"] == 0:30 suggestions.append("Include online security in their plan as a free trial.")31 if customer["Partner"] == 0 and customer["Dependents"] == 0:32 suggestions.append("Offer individual loyalty rewards or referral bonuses.")33 if customer.get("tenure", 0) < 3:34 suggestions.append("Assign a dedicated onboarding assistant to help during the first months.")35 if customer["StreamingTV"] == 0 and customer.get("InternetService_Fiber optic", 0) == 1:36 suggestions.append("Bundle free streaming service for 3 months with high-speed fiber.")37 if customer["PaperlessBilling"] == 1:38 suggestions.append("Offer cashback for using paperless billing.")39 40 addon_services = ["OnlineSecurity", "OnlineBackup", "DeviceProtection", "TechSupport", "StreamingTV"]41 if all(customer[feature] == 0 for feature in addon_services):42 suggestions.append("Offer a bundled package with multiple services at a discounted rate.")43 44 if not suggestions:45 suggestions.append("Send a satisfaction survey with a loyalty reward.")46 47 return "\n - " + "\n - ".join(suggestions)48 49# Main prediction50def predict_churn(51 SeniorCitizen, Partner, Dependents, tenure, PhoneService, MultipleLines,52 InternetService, OnlineSecurity, OnlineBackup, DeviceProtection, TechSupport,53 StreamingTV, StreamingMovies, Contract, PaperlessBilling, PaymentMethod,54 MonthlyCharges, TotalCharges55):56 encoded = {57 "SeniorCitizen": int(SeniorCitizen),58 "Partner": 1 if Partner == "Yes" else 0,59 "Dependents": 1 if Dependents == "Yes" else 0,60 "PhoneService": 1 if PhoneService == "Yes" else 0,61 "MultipleLines": 1 if MultipleLines == "Yes" else 0,62 "OnlineSecurity": 1 if OnlineSecurity == "Yes" else 0,63 "OnlineBackup": 1 if OnlineBackup == "Yes" else 0,64 "DeviceProtection": 1 if DeviceProtection == "Yes" else 0,65 "TechSupport": 1 if TechSupport == "Yes" else 0,66 "StreamingTV": 1 if StreamingTV == "Yes" else 0,67 "StreamingMovies": 1 if StreamingMovies == "Yes" else 0,68 "PaperlessBilling": 1 if PaperlessBilling == "Yes" else 0,69 "MonthlyCharges": float(MonthlyCharges),70 "TotalCharges": float(TotalCharges),71 "PaymentMethod_Credit card (automatic)": 1 if PaymentMethod == "Credit card (automatic)" else 0,72 "PaymentMethod_Electronic check": 1 if PaymentMethod == "Electronic check" else 0,73 "PaymentMethod_Mailed check": 1 if PaymentMethod == "Mailed check" else 0,74 "InternetService_Fiber optic": 1 if InternetService == "Fiber optic" else 0,75 "InternetService_No": 1 if InternetService == "No" else 0,76 "Contract_One year": 1 if Contract == "One year" else 0,77 "Contract_Two year": 1 if Contract == "Two year" else 0,78 "TenureGroup_Experienced": 1 if 12 < tenure <= 36 else 0,79 "TenureGroup_Loyal": 1 if tenure > 36 else 0,80 "tenure": tenure81 }82 83 input_df = pd.DataFrame([encoded])84 for col in expected_columns:85 if col not in input_df.columns:86 input_df[col] = 087 input_df = input_df[expected_columns]88 89 prediction = model.predict(input_df)[0]90 churn_prob = model.predict_proba(input_df)[:, 1][0]91 result = "Churn" if prediction == 1 else "No Churn"92 93 if prediction == 1:94 suggestion = generate_suggestion(encoded)95 return f"⚠️ **Prediction**: {result} (Probability: {churn_prob:.2%})\n\n🤖 **Suggestions**:{suggestion}"96 else:97 return f"✅ **Prediction**: {result} (Probability: {churn_prob:.2%})"98 99# Sample customers100def get_customers_from_db():101 return [102 (0, 'Yes', 'No', 6, 'Yes', 'No', 'DSL', 'Yes', 'No', 'Yes', 'No', 'Yes', 'No', 'Month-to-month', 'Yes', 'Credit card (automatic)', 500.00, 200.00),103 (1, 'No', 'Yes', 12, 'No', 'No', 'DSL', 'No', 'Yes', 'No', 'Yes', 'No', 'Yes', 'Month-to-month', 'No', 'Credit card (automatic)', 300.00, 3600.00),104 (0, 'Yes', 'Yes', 24, 'Yes', 'Yes', 'DSL', 'Yes', 'Yes', 'Yes', 'Yes', 'Yes', 'Yes', 'Month-to-month', 'Yes', 'Credit card (automatic)', 150.00, 3600.00)105 ]106 107def predict_all_customers():108 customers = get_customers_from_db()109 results = []110 111 for i, row in enumerate(customers, start=1):112 result = predict_churn(*row)113 results.append(f"### 🧑💼 Customer {i}:\n{result}")114 115 return "\n\n---\n\n".join(results)116 117# Individual interface118individual_app = gr.Interface(119 fn=predict_churn,120 inputs=[121 gr.Radio(["0", "1"], label="Senior Citizen"),122 gr.Radio(["Yes", "No"], label="Partner"),123 gr.Radio(["Yes", "No"], label="Dependents"),124 gr.Slider(0, 72, step=1, label="Tenure (months)"),125 gr.Radio(["Yes", "No"], label="Phone Service"),126 gr.Radio(["Yes", "No"], label="Multiple Lines"),127 gr.Dropdown(["DSL", "Fiber optic", "No"], label="Internet Service"),128 gr.Radio(["Yes", "No"], label="Online Security"),129 gr.Radio(["Yes", "No"], label="Online Backup"),130 gr.Radio(["Yes", "No"], label="Device Protection"),131 gr.Radio(["Yes", "No"], label="Tech Support"),132 gr.Radio(["Yes", "No"], label="Streaming TV"),133 gr.Radio(["Yes", "No"], label="Streaming Movies"),134 gr.Dropdown(["Month-to-month", "One year", "Two year"], label="Contract"),135 gr.Radio(["Yes", "No"], label="Paperless Billing"),136 gr.Dropdown(137 ["Credit card (automatic)", "Electronic check", "Mailed check", "Bank transfer (automatic)"],138 label="Payment Method"139 ),140 gr.Number(label="Monthly Charges"),141 gr.Number(label="Total Charges"),142 ],143 outputs=gr.Textbox(),144 title="📉 Individual Customer Churn Prediction",145 description="Fill in customer data to predict churn and receive suggestions."146)147 148# Bulk prediction interface149bulk_app = gr.Interface(150 fn=predict_all_customers,151 inputs=[],152 outputs=gr.Markdown(label="Results"),153 title="📂 Bulk Prediction for Customers",154 description="Displays churn prediction and suggestions for multiple customers."155)156 157# Tabs for both interfaces158demo = gr.TabbedInterface(159 interface_list=[individual_app, bulk_app],160 tab_names=["🧍 Individual Prediction", "📊 Bulk Prediction"]161)162 163if __name__ == "__main__":164 demo.launch()165 