🚀 Live Interactive Web Application: https://customer-churn-prediction-am9rjlvuk7zwa8w.streamlit.app/
An enterprise-grade, end-to-end Machine Learning system that predicts telecom customer churn with 83.8% ROC-AUC and ~80% Recall, delivers automated risk stratification, and surfaces proactive retention playbooks via an interactive Streamlit analytics application.
Customer acquisition in the telecommunications industry costs 5× to 7× more than customer retention. A 5% reduction in churn can boost company profitability by 25% to 95%.
This project delivers a production-structured Machine Learning solution designed to identify at-risk telecom subscribers before they cancel services. Rather than relying on standard out-of-the-box classification, this project implements:
- Business-First Metric Optimization: Prioritizes Recall (Sensitivity) and ROC-AUC to minimize costly False Negatives (unidentified churners).
- Domain Feature Engineering: Formulates 5 high-impact behavioral indicators capturing customer commitment and service breadth.
- Production-Ready Architecture: Clean separation of concerns with modular ETL, training, and decoupled inference engine (
src/), zero-leakage scikit-learn transformers, and an interactive Streamlit UI for both real-time individual assessment and bulk CSV batch scoring.
Telecom operators experience significant Monthly Recurring Revenue (MRR) loss due to customer attrition. Retention teams frequently operate reactively—reaching out only after a customer initiates cancellation or downgrades, when retention probability is lowest. Moreover, generic retention promotions waste marketing budget on customers who were never at risk.
An intelligent, proactive Churn Early-Warning System that:
- Scores Churn Probability: Quantifies each customer's risk from 0% to 100% using a calibrated XGBoost ensemble classifier.
- Segments Customers into Risk Tiers: Categorizes accounts into Low Risk (<35%), Medium Risk (35%–65%), and High Risk (>65%).
- Prescribes Actionable Retention Playbooks: Recommends targeted operational interventions (contract incentives, service bundles, payment method migration) based on predicted churn drivers.
- Supports Dual Operational Modes: Instant single-subscriber scoring for customer service representatives and batch CSV inference for CRM marketing automation.
flowchart TD
subgraph Data_Layer ["1. Data Ingestion & Preprocessing"]
A[Raw Telco Dataset] --> B[Data Cleaning & Missing Value Imputation]
B --> C[Domain Feature Engineering]
C --> D[Stratified Train/Test Split]
end
subgraph Pipeline_Layer ["2. Machine Learning Pipeline"]
D --> E[ColumnTransformer Pipeline]
E -->|One-Hot Encoding| F[Categorical Features]
E -->|StandardScaler| G[Numerical Features]
F & G --> H[Model Benchmark & Training]
H -->|Class-Weighted Logistic Reg| I1[Logistic Regression]
H -->|Cost-Sensitive Ensemble| I2[Random Forest]
H -->|scale_pos_weight Tuned| I3[XGBoost Classifier]
I1 & I2 & I3 --> J{Composite Evaluation<br/>ROC-AUC 60% + Recall 40%}
J -->|Winner Artifact| K[Serialized Models & Transformers]
end
subgraph Serving_Layer ["3. Decoupled Inference Engine"]
K --> L[ChurnPredictor Class<br/>src/predict.py]
end
subgraph Presentation_Layer ["4. Streamlit Interactive Dashboard"]
L --> M[Single Customer Risk Scoring]
L --> N[Batch CSV File Scoring]
M --> O[Instant Risk Badge & Playbook]
N --> P[Exportable CSV & Aggregate Analytics]
end
style I3 fill:#e1f5fe,stroke:#0288d1,stroke-width:2px
style K fill:#e8f8f5,stroke:#27ae60,stroke-width:2px
style Serving_Layer fill:#fff8e1,stroke:#f39c12,stroke-width:2px
- Dataset: IBM Telco Customer Churn dataset comprising 7,043 customers across 21 demographic, service, and billing attributes.
- Anomalies Handled: Discovered subtle blank strings (
" ") inTotalChargesfor new customers withtenure == 0. Converted column to numeric and resolved zero-tenure records without data loss. - Target Distribution: Evaluated class balance (~73.5% non-churn vs. ~26.5% churn). A naive model predicting majority class achieves 73.5% accuracy but detects 0% of churners, establishing the need for cost-sensitive learning.
Extracted high-signal telecom behavioral features based on churn heuristics:
TotalServices: Count of active add-on subscriptions (OnlineSecurity,OnlineBackup,DeviceProtection,TechSupport,StreamingTV,StreamingMovies). Customers with higher service adoption exhibit substantially lower attrition due to ecosystem lock-in.AverageMonthlyCost: Computed asTotalCharges / (tenure + 1)to assess spending trajectory and cost inflation relative to tenure.IsMonthToMonth: Binary indicator highlighting month-to-month contracts (the single highest vulnerability segment).HasFiberOptic: Binary indicator identifying fiber optic subscribers (who experience higher churn when missing technical support).AutoPayment: Binary indicator for automated payment methods (Bank transfer,Credit card), which correlate with stronger retention compared to electronic checks.
- Implemented a unified
ColumnTransformerencapsulated insrc/data_preprocessing.py:- Categorical Columns (15 features): Encoded with
OneHotEncoder(drop='first', handle_unknown='ignore'). - Numerical Columns (9 features): Standardized using
StandardScaler().
- Categorical Columns (15 features): Encoded with
- Pipeline fitted strictly on training splits to prevent data leakage, then serialized as a reusable
joblibartifact.
Trained and compared three distinct model families, optimizing with class weighting to counteract the ~3:1 class imbalance:
- Logistic Regression: Regularized linear baseline (
class_weight='balanced'). - Random Forest Classifier: Non-linear ensemble (
n_estimators=150,max_depth=8,class_weight='balanced'). - XGBoost Classifier (Winner): Gradient boosted decision trees configured with:
scale_pos_weight = (len(negative) / len(positive))to penalize false negatives.- Constrained tree depth (
max_depth=4) and conservative learning rate (0.05) to safeguard against overfitting.
Models were evaluated on a held-out, stratified test set (20% sample):
| Model | Accuracy | Precision | Recall (Sensitivity) | F1-Score | ROC-AUC | Primary Selection Rationale |
|---|---|---|---|---|---|---|
| Logistic Regression | 73.13% | 0.4966 | 79.14% | 0.6103 | 0.8376 | Fast baseline, high recall |
| Random Forest | 74.77% | 0.5170 | 77.27% | 0.6195 | 0.8361 | Balanced tree ensemble |
| XGBoost Classifier (Selected) | 73.70% | 0.5034 | 79.95% | 0.6178 | 0.8378 | Highest Recall & ROC-AUC |
In customer churn, the business cost of a False Negative (missing a customer who cancels, forfeiting lifetime value) is drastically higher than a False Positive (offering a retention discount to a loyal customer). Therefore, the winning model was selected via a composite objective prioritizing ROC-AUC (60%) and Recall (40%), successfully capturing ~80% of all at-risk customers.
Feature importance and exploratory analysis revealed the key drivers behind customer attrition:
| Churn Driver | Observation | Actionable Retention Playbook |
|---|---|---|
| Month-to-Month Contract | Customers on monthly contracts churn at ~42%, compared to <11% for 1-year and <3% for 2-year contracts. | Target month-to-month subscribers with a contract conversion bonus (e.g., 15% discount for switching to an annual contract). |
| Fiber Optic without Tech Support | High attrition in fiber optic subscribers who lack online security or technical assistance. | Bundle complimentary Tech Support & Online Security for 6 months for all high-speed internet subscribers. |
| Electronic Check Payments | Customers paying via manual electronic checks exhibit nearly 2× higher churn than auto-debit subscribers. | Offer a one-time bill credit ($10) for enrolling in Auto-Pay via Credit Card or Bank Transfer. |
| Single-Service Accounts | Customers with low TotalServices score lack product stickiness. |
Deploy personalized multi-service bundle offers to increase customer engagement across services. |
The interactive dashboard (app.py) provides non-technical stakeholders and retention teams with immediate access to model intelligence:
- Single Customer Risk Assessment:
- Sliders and select boxes across Demographics, Subscribed Services, and Billing.
- Dynamic churn probability meter with real-time risk classification:
- 🟢 Low Risk (<35%): Stable account; retain with loyalty perks.
- 🟡 Medium Risk (35%–65%): Moderate risk; send engagement surveys and auto-pay promotions.
- 🔴 High Risk (>65%): Urgent risk; triggers proactive outreach and contract incentives.
- Batch CSV Prediction:
- Bulk upload capability for entire customer databases.
- Generates predictions, appends probability scores and risk badges, displays summary metrics, and enables 1-click CSV download.
- Model Insights & Architecture View:
- On-screen summary of data pipeline, engineered features, and algorithmic methodology for full transparency.
Customer Churn Prediction/
├── app.py # Interactive Streamlit Web Application
├── requirements.txt # Project dependencies
├── README.md # Recruiter-facing system documentation
├── data/
│ ├── raw/ # Original IBM Telco customer dataset
│ └── processed/ # Cleaned dataset (cleaned_churn.csv)
├── models/
│ ├── preprocessor.joblib # Serialized Scikit-Learn ColumnTransformer
│ └── churn_model.joblib # Serialized XGBoost Classifier artifact
├── notebooks/
│ ├── 01_data_understanding.ipynb # Column profiling & data dictionary validation
│ ├── 02_data_cleaning.ipynb # Missing value handling & type conversions
│ ├── 03_eda_and_feature_engineering.ipynb # Bivariate analysis & feature generation
│ └── 04_model_building.ipynb # Benchmark experiments & hyperparameter tuning
└── src/
├── __init__.py
├── data_preprocessing.py # Feature engineering functions & ColumnTransformer
├── model_training.py # Multi-model training, evaluation & artifact exporter
└── predict.py # Reusable inference engine (single & batch inference)
- Python 3.10 or higher
- Git
# Clone the repository
git clone https://github.com/soumyadip-das-dev/Customer-Churn-Prediction.git
cd Customer-Churn-Prediction
# Create and activate virtual environment
python -m venv venv
# Windows:
venv\Scripts\activate
# Linux/macOS:
# source venv/bin/activate
# Install dependencies
pip install -r requirements.txtTo retrain the benchmark models and reproduce the serialized artifacts in models/:
python src/model_training.pyLaunch the web interface locally:
streamlit run app.pyThe dashboard will open automatically in your browser at http://localhost:8501.
- Programming Language: Python 3.10+
- Machine Learning & Modeling: Scikit-Learn, XGBoost
- Data Manipulation & Preprocessing: Pandas, NumPy
- Pipeline & Serialization: Scikit-Learn
ColumnTransformer,Pipeline, Joblib - Exploratory Data Analysis: Matplotlib, Seaborn
- Application & Dashboard: Streamlit
- Development & Versioning: Git, Jupyter Notebooks
Soumyadip Das
- GitHub: @soumyadip-das-dev
- Role: Data Scientist / Machine Learning Engineer