Skip to content
reyyishreyasPublic

About

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

14 Commits

Folders and files

Repository files navigation

TRICP Logo

TRICP

Telecom Retention Intelligence & Churn Predictor

An end-to-end AI-powered customer churn prediction platform that combines explainable machine learning, intelligent decision automation, and personalized retention workflows.

GitHub FastAPI React ML Python


What is TRICP?

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.

Demo Screenshots

Dashboard User Analysis Simulation
dashboard analysis simulation

AI Decision Pipeline

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.


Core Features

1. Single Prediction — On-Demand Risk Analysis

Enter a customer's profile to instantly receive:

  • Churn Probability generated by the trained stacking ensemble model.
  • Risk Classification (Low, Medium, or High).
  • 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.


2. Bulk Customer Analysis & Workflow Automation

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.


3. What-If Simulation

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.


4. Explainable AI Dashboard

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.


5. Intelligent Retention Recommendation Engine

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.


Technology Stack

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)

Repository Structure

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

Machine Learning Architecture

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

Feature Engineering

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.


Handling Class Imbalance

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.


Ensemble Learning

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 Performance

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.


REST API

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

API Endpoints

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

Prediction Workflow

Every prediction follows the same workflow:

  1. Receive customer information through the REST API.
  2. Preprocess and engineer input features.
  3. Run inference using the trained stacking ensemble.
  4. Compute churn probability.
  5. Identify the most influential features contributing to the prediction.
  6. Map these features to predefined business recommendations.
  7. Select the most suitable retention email template.
  8. Return the prediction, explanations, and recommendations.

Example Prediction Request

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
}'

Setup & Running Locally

Prerequisites

  • Python 3.11+
  • Node.js 18+
  • Git

1. Clone the Repository

git clone https://github.com/reyyishreyas/churn_predictor.git

cd churn_predictor

2. Backend Setup

python3 -m venv venv

source venv/bin/activate

# Windows

venv\Scripts\activate

pip install -r backend/requirements.txt

3. Train the Machine Learning Model

The training script generates all required model artifacts inside the backend/artifacts directory.

python backend/train_pipeline.py

If the artifacts already exist, this step can be skipped.


4. Configure Environment Variables

cp backend/.env.example backend/.env

Configure 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=threshold

If SMTP credentials are omitted, emails are logged instead of being sent.


5. Start the Backend

cd backend

uvicorn app.main:app --reload --host 0.0.0.0 --port 8000

Backend:

http://localhost:8000

API Documentation:

http://localhost:8000/docs

6. Start the Frontend

cd frontend-react

npm install

npm run dev

Frontend:

http://localhost:5173

Environment Variables

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 .env file to version control.


Batch CSV Format

The batch prediction endpoint accepts customer datasets in CSV format.

Required Columns

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

Optional Behavioral Features

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.


Explainable AI Workflow

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:

  1. Generates churn probability.
  2. Identifies the strongest contributing features.
  3. Ranks those features by importance.
  4. Maps important features to predefined retention strategies.
  5. Automatically selects the most appropriate email template.
  6. Dispatches the email through the SMTP workflow.

This makes the prediction process transparent, actionable, and easier for business teams to understand.


Recommendation Workflow

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.


Notebooks

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.


churn_model.ipynb

This notebook contains the primary machine learning development pipeline.

It includes:

  • 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.


Training Pipeline

The notebook performs the following sequence:

Dataset
     │
     ▼
Cleaning
     │
     ▼
Feature Engineering
     │
     ▼
Encoding
     │
     ▼
SMOTE
     │
     ▼
Scaling
     │
     ▼
Model Training
     │
     ▼
Evaluation
     │
     ▼
Artifact Generation

Feature Engineering

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.


Model Evaluation

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.


churnpredictordataset.ipynb

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.


Running the Notebooks

Install Jupyter if required:

pip install notebook

Launch:

jupyter notebook notebooks/

Deployment

Backend (Docker)

docker build -t tricp-backend ./backend

docker run \
-p 8000:8000 \
--env-file backend/.env \
tricp-backend

Backend API:

http://localhost:8000

Interactive Documentation:

http://localhost:8000/docs

Frontend

cd frontend-react

npm run build

The 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.


Project Highlights

  • 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

Future Improvements

  • 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

Contributing

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.


Author

Shreyas


Built with ❤️ using

FastAPI • React • TypeScript • scikit-learn • XGBoost • LightGBM • Machine Learning

If you found this project useful, consider ⭐ starring the repository.

About

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages