An end-to-end AI-powered customer churn prediction platform that combines explainable machine learning, intelligent decision automation, and personalized retention workflows.
TRICP bridges the gap between machine learning predictions and real business actions.
Instead of only predicting whether a customer is likely to churn, the platform explains why the prediction was made, identifies the most influential churn factors, recommends appropriate retention strategies, and automatically delivers personalized retention emails through an automated workflow.
The application provides an end-to-end AI pipeline that combines:
- Explainable Machine Learning
- Feature Engineering
- REST API-based prediction services
- Automated business decision workflows
- Personalized customer engagement
TRICP enables businesses to:
- Predict customer churn using a production-ready stacking ensemble model.
- Explain predictions through feature-level attribution and root-cause analysis.
- Run bulk prediction campaigns for thousands of customers.
- Automatically trigger retention workflows based on predicted churn drivers.
- Evaluate business interventions using an interactive simulation engine.
- Visualize model insights through performance metrics and feature importance dashboards.
| Dashboard | User Analysis | Simulation |
|---|---|---|
Customer Data
│
▼
Feature Engineering
│
▼
Stacking Ensemble Model
│
▼
Churn Probability Prediction
│
▼
Feature Importance Analysis
│
▼
Root Cause Identification
│
▼
Recommendation Engine
│
▼
Email Template Selection
│
▼
SMTP Email Delivery
Rather than sending generic retention campaigns, TRICP first identifies the strongest contributors to churn before selecting the most relevant intervention strategy and email template.
Enter a customer's profile to instantly receive:
- Churn Probability generated by the trained stacking ensemble model.
- Risk Classification (
Low,Medium, orHigh). - Feature-Level Root Cause Analysis highlighting the strongest contributors to churn.
- Personalized Retention Recommendations generated by mapping the identified churn factors to predefined business strategies.
This allows customer success teams to understand both the prediction and the reasoning behind it.
Upload an entire customer dataset and TRICP automatically:
- Processes every customer through the complete ML prediction pipeline.
- Predicts churn probability for every record.
- Segments users into appropriate risk categories.
- Identifies the dominant churn drivers for each customer.
- Selects the most suitable retention strategy.
- Automatically dispatches personalized retention emails using Python SMTP.
- Generates an enriched CSV containing:
- Predicted churn probability
- Risk category
- Recommended retention strategy
- Customer engagement information
This enables large-scale retention campaigns with minimal manual effort.
The simulation engine allows business teams to evaluate possible interventions before applying them.
Users can modify attributes such as:
- Contract Type
- Login Frequency
- Feature Usage
- Payment Failures
- Customer Engagement
The system recalculates churn probability in real time, making it easy to compare how behavioral changes influence customer retention.
TRICP focuses on model transparency rather than treating predictions as black boxes.
The Insights dashboard provides:
- Feature Importance rankings
- Model Evaluation Metrics
- Performance Comparison across multiple models
- Dataset-level analytics
- Prediction explainability
This allows stakeholders to understand how and why predictions are generated.
Rather than generating generic responses, the recommendation engine analyzes the highest contributing churn factors identified by the machine learning model and automatically selects the most appropriate retention strategy.
The system then chooses one of 8 predefined retention email templates, ensuring that every customer receives a message relevant to their specific churn risk.
| Retention Strategy | Trigger Condition |
|---|---|
| High-Value Customer | High spending with elevated churn probability |
| Billing Issue | Payment failures or electronic check payments |
| Customer Inactivity | Last login ≥ 21 days |
| Early Lifecycle | Customer tenure ≤ 6 months |
| Price Sensitivity | Monthly charges ≥ $85 |
| Low Engagement | Low login frequency or feature usage |
| Low Product Adoption | Fewer than 3 active services |
| Contract Commitment | Month-to-month contracts |
The recommendation engine uses feature importance and business rules to map each customer to the most suitable retention workflow.
| Layer | Technology |
|---|---|
| Backend | Python, FastAPI, Uvicorn |
| Frontend | React 19, TypeScript, Vite |
| Machine Learning | scikit-learn, XGBoost, LightGBM, SMOTE |
| ML Serving | Joblib, Stacking Ensemble |
| APIs | REST APIs, FastAPI |
| Explainability | Feature Importance Analysis |
| Automation | Rule-Based Recommendation Engine, Python SMTP |
| Charts | Recharts |
| UI | Tailwind CSS, shadcn/ui, Radix UI |
| HTTP Client | Axios |
| Dataset | Telco Customer Churn Dataset (7,043 Records) |
churn_predictor/
│
├── logo.png # TRICP brand logo
│
├── backend/
│ ├── train_pipeline.py # End-to-end ML training pipeline
│ ├── requirements.txt
│ ├── .env.example # Environment configuration
│ ├── Dockerfile
│ │
│ ├── app/
│ │ ├── main.py # FastAPI application entry point
│ │ ├── config/
│ │ │ └── settings.py # Application configuration
│ │ ├── models/
│ │ │ ├── preprocessor.py # Data preprocessing pipeline
│ │ │ └── schemas.py # Request & response schemas
│ │ ├── routes/
│ │ │ ├── churn.py # Prediction & analysis endpoints
│ │ │ └── health.py # Health check endpoint
│ │ ├── services/
│ │ │ ├── artifact_store.py
│ │ │ ├── batch_service.py
│ │ │ ├── email_service.py
│ │ │ ├── email_templates.py
│ │ │ ├── engagement_service.py
│ │ │ ├── explainability_service.py
│ │ │ ├── insights_service.py
│ │ │ ├── intervention_engine.py
│ │ │ ├── prediction_service.py
│ │ │ ├── recommendation_service.py
│ │ │ ├── segmentation_service.py
│ │ │ └── simulation_service.py
│ │ └── utils/
│ │ ├── feature_helpers.py
│ │ └── logger.py
│ │
│ ├── artifacts/
│ │ ├── model.pkl
│ │ ├── scaler.pkl
│ │ ├── preprocessor.pkl
│ │ ├── feature_columns.pkl
│ │ ├── logistic_regression.pkl
│ │ ├── random_forest.pkl
│ │ └── metadata.json
│ │
│ ├── data/
│ │ └── churn.csv
│ │
│ └── logs/
│
├── frontend-react/
│ ├── src/
│ │ ├── pages/
│ │ ├── components/
│ │ ├── lib/
│ │ └── App.tsx
│ └── package.json
│
└── notebooks/
├── churn_model.ipynb
└── churnpredictordataset.ipynb
TRICP is powered by a Stacking Ensemble Machine Learning model trained on the Telco Customer Churn Dataset (7,043 customer records).
The training pipeline focuses on improving prediction accuracy while maintaining model interpretability through feature-level explanations.
Raw Customer Data
│
▼
Data Cleaning
│
▼
Feature Engineering
│
▼
Categorical Encoding
│
▼
SMOTE Oversampling
│
▼
Feature Scaling
│
▼
Stacking Ensemble
│
├── XGBoost
├── LightGBM
├── Gradient Boosting
└── Random Forest
│
▼
Logistic Regression Meta Learner
│
▼
Churn Probability Prediction
│
▼
Feature Importance & Root Cause Analysis
The model derives additional business features including:
- Charges Per Month
- Tenure Bucket
- Service Count
- High Value Customer
- Contract Risk
- Monthly-to-Total Charge Ratio
These engineered features improve prediction quality while providing more meaningful explanations.
To improve recall for churned customers, the training pipeline applies:
- SMOTE (Synthetic Minority Oversampling Technique)
- StandardScaler
- Stratified Train/Test Split
This helps the model better identify customers who are at risk of leaving.
Instead of relying on a single model, TRICP combines predictions from multiple algorithms:
- XGBoost
- LightGBM
- Gradient Boosting
- Random Forest
These predictions are combined using a Logistic Regression meta-learner to generate the final churn probability.
This ensemble approach provides improved robustness and predictive performance compared to individual models.
| Model | Accuracy | ROC AUC | Precision | Recall |
|---|---|---|---|---|
| Stacking Ensemble | 76.9% | 82.7% | 55.0% | 70.1% |
| Logistic Regression | 74.8% | 84.3% | 51.7% | 77.5% |
| Random Forest | 74.2% | 82.4% | 51.0% | 75.9% |
XGBoost and LightGBM are used as base learners within the stacking ensemble and contribute to the final prediction.
TRICP exposes a FastAPI backend that provides prediction, simulation, explainability, and batch-processing services through REST APIs.
Interactive API documentation is available at:
http://localhost:8000/docs
| Method | Endpoint | Description |
|---|---|---|
| GET | /health |
Application health check |
| POST | /predict |
Predict customer churn and generate recommendations |
| POST | /simulate |
Compare churn probability before and after changing customer attributes |
| POST | /batch-predict |
Bulk prediction and automated retention workflow |
| GET | /insights |
Model insights and feature importance |
| GET | /model-metrics |
Model evaluation metrics |
Every prediction follows the same workflow:
- Receive customer information through the REST API.
- Preprocess and engineer input features.
- Run inference using the trained stacking ensemble.
- Compute churn probability.
- Identify the most influential features contributing to the prediction.
- Map these features to predefined business recommendations.
- Select the most suitable retention email template.
- Return the prediction, explanations, and recommendations.
curl -X POST http://localhost:8000/predict \
-H "Content-Type: application/json" \
-d '{
"customer_id":"cust-001",
"gender":"Female",
"SeniorCitizen":0,
"Partner":"Yes",
"Dependents":"No",
"tenure":12,
"PhoneService":"Yes",
"InternetService":"Fiber optic",
"Contract":"Month-to-month",
"PaymentMethod":"Electronic check",
"MonthlyCharges":79.90,
"TotalCharges":959.0,
"days_since_last_login":18,
"avg_logins_per_week":2.1,
"feature_usage_score":42.0,
"payment_failures_90d":1
}'- Python 3.11+
- Node.js 18+
- Git
git clone https://github.com/reyyishreyas/churn_predictor.git
cd churn_predictorpython3 -m venv venv
source venv/bin/activate
# Windows
venv\Scripts\activate
pip install -r backend/requirements.txtThe training script generates all required model artifacts inside the backend/artifacts directory.
python backend/train_pipeline.pyIf the artifacts already exist, this step can be skipped.
cp backend/.env.example backend/.envConfigure your SMTP credentials if email delivery is required.
GMAIL_ADDRESS=your@gmail.com
GMAIL_APP_PASSWORD=your-app-password
MAIL_FROM_NAME=Retention Team
CHURN_TRIGGER_THRESHOLD=0.60
EMAIL_BATCH_MIN_RISK=thresholdIf SMTP credentials are omitted, emails are logged instead of being sent.
cd backend
uvicorn app.main:app --reload --host 0.0.0.0 --port 8000Backend:
http://localhost:8000
API Documentation:
http://localhost:8000/docs
cd frontend-react
npm install
npm run devFrontend:
http://localhost:5173
| Variable | Default | Description |
|---|---|---|
CHURN_TRIGGER_THRESHOLD |
0.60 |
Minimum churn probability required to trigger a retention workflow |
EMAIL_BATCH_MIN_RISK |
threshold |
Controls which customers receive automated retention emails (threshold, medium, or high) |
GMAIL_ADDRESS |
— | Gmail account used for SMTP email delivery |
GMAIL_APP_PASSWORD |
— | Gmail App Password for SMTP authentication |
SMTP_HOST |
smtp.gmail.com |
SMTP server hostname |
SMTP_PORT |
587 |
SMTP server port |
MAIL_FROM_NAME |
Retention Team |
Display name for outgoing emails |
EMAIL_MODE |
Auto | SMTP mode or logging mode |
Note: Never commit your
.envfile to version control.
The batch prediction endpoint accepts customer datasets in CSV format.
user_id (or customer_id)
email
gender
SeniorCitizen
Partner
Dependents
tenure
PhoneService
MultipleLines
InternetService
OnlineSecurity
OnlineBackup
DeviceProtection
TechSupport
StreamingTV
StreamingMovies
Contract
PaperlessBilling
PaymentMethod
MonthlyCharges
TotalCharges
Providing these additional behavioral features improves prediction quality.
days_since_last_login
avg_logins_per_week
avg_session_duration_minutes
feature_usage_score
payment_failures_90d
support_tickets_30d
activity_trend_pct
The system ignores the Churn column (if present), ensuring predictions remain unbiased.
Unlike traditional prediction systems that only return a probability score, TRICP also explains why a customer is likely to churn.
For every prediction the system:
- Generates churn probability.
- Identifies the strongest contributing features.
- Ranks those features by importance.
- Maps important features to predefined retention strategies.
- Automatically selects the most appropriate email template.
- Dispatches the email through the SMTP workflow.
This makes the prediction process transparent, actionable, and easier for business teams to understand.
Customer Prediction
│
▼
Identify Highest Impact Features
│
▼
Business Rule Evaluation
│
▼
Retention Strategy Selection
│
▼
Email Template Selection
│
▼
SMTP Email Delivery
Instead of sending generic promotional emails, the recommendation engine uses the model's explanations to determine the most relevant customer intervention.
The notebooks directory contains the experiments used during model development and validation.
notebooks/
├── churn_model.ipynb
└── churnpredictordataset.ipynb
These notebooks document the complete machine learning development lifecycle, from exploratory analysis to the final production-ready model.
This notebook contains the primary machine learning development pipeline.
- Dataset preprocessing
- Missing value handling
- Target encoding
- Feature engineering
- Feature transformation
- SMOTE oversampling
- Model training
- Hyperparameter tuning
- Ensemble model creation
- Model evaluation
- Artifact generation
The notebook served as the foundation for the production training pipeline implemented in backend/train_pipeline.py.
The notebook performs the following sequence:
Dataset
│
▼
Cleaning
│
▼
Feature Engineering
│
▼
Encoding
│
▼
SMOTE
│
▼
Scaling
│
▼
Model Training
│
▼
Evaluation
│
▼
Artifact Generation
Additional business-oriented features include:
- Charges Per Month
- Monthly-to-Total Charge Ratio
- Tenure Buckets
- Service Count
- Contract Risk
- High Value Customer
These engineered features improve prediction quality while making the model easier to interpret.
The notebook evaluates multiple algorithms before selecting the final stacking ensemble.
Metrics include:
- Accuracy
- ROC-AUC
- Precision
- Recall
- F1 Score
- Confusion Matrix
The final production model is chosen based on overall predictive performance rather than a single metric.
This notebook focuses on exploratory data analysis and understanding customer behavior before model training.
It includes:
- Feature distributions
- Correlation analysis
- Missing value inspection
- Target distribution
- Class imbalance visualization
- Statistical summaries
These analyses guided the feature engineering decisions used in the production pipeline.
Install Jupyter if required:
pip install notebookLaunch:
jupyter notebook notebooks/docker build -t tricp-backend ./backend
docker run \
-p 8000:8000 \
--env-file backend/.env \
tricp-backendBackend API:
http://localhost:8000
Interactive Documentation:
http://localhost:8000/docs
cd frontend-react
npm run buildThe production build is generated inside:
frontend-react/dist
The frontend can be deployed to platforms such as:
- Vercel
- Netlify
- Cloudflare Pages
- AWS S3
Configure:
VITE_API_URL=https://your-backend-url.com
to connect the frontend with the deployed FastAPI backend.
- Production-ready FastAPI backend with REST APIs
- Explainable Machine Learning pipeline
- Feature engineering and ensemble learning
- Automated customer segmentation
- Intelligent recommendation engine
- Personalized retention workflow
- Bulk customer prediction support
- Interactive business simulation tools
- Modular backend architecture
- React + TypeScript frontend
- Docker-ready deployment
- Multi-tenant organization support
- Customer history dashboard
- Real-time streaming predictions
- Advanced explainability using SHAP values
- Configurable retention strategies
- Multi-channel notifications (Email, SMS, WhatsApp)
- A/B testing for retention campaigns
- Model monitoring and drift detection
Contributions, suggestions, and improvements are always welcome.
If you would like to improve the project, feel free to open an issue or submit a pull request.
Shreyas