Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Customer Churn Prediction

Python scikit-learn Pandas Jupyter License

A machine learning project that predicts customer churn for a telecommunications company, combining supervised classification (Logistic Regression, Decision Tree) with unsupervised segmentation (K-Means) to support data-driven retention strategies.


Overview

Customer churn — when a client stops doing business with a company — is one of the costliest problems for subscription-based businesses like telecom providers. This project builds an end-to-end pipeline that:

  1. Cleans and prepares raw customer data
  2. Trains and compares two classification models to predict which customers are likely to churn
  3. Segments the customer base with clustering to reveal distinct behavioral profiles
  4. Translates both results into actionable business recommendations

Objectives

  • Clean raw customer data
  • Explore customer behavior
  • Train predictive models
  • Evaluate model performance
  • Identify key factors related to churn

Dataset

This project uses the Telco Customer Churn dataset (originally published by IBM), containing customer demographics, account information, subscribed services, and the churn label.

Rows 7,043
Columns 21
Target variable Churn (Yes / No)
Key features tenure, MonthlyCharges, TotalCharges, Contract, InternetService, PaymentMethod, etc.

The dataset (Telco Customer Churn.csv) is included in this repository at the project root, so the notebook runs out of the box with no separate download step.

Tech Stack

Category Tools
Language Python 3
Data manipulation Pandas
Machine Learning scikit-learn — Logistic Regression, Decision Tree, K-Means, preprocessing, metrics
Visualization Matplotlib, Seaborn
Environment Jupyter Notebook / Google Colab

Repository Structure

customer-churn-prediction/
├── Customer_Churn_Prediction.ipynb   # Main notebook (analysis, modeling, evaluation)
├── Telco Customer Churn.csv          # Dataset
├── requirements.txt                  # Project dependencies
├── README.md                         # Project documentation
└── assets/                           # Exported charts used in this README
    ├── confusion_matrix_logistic_regression.png
    ├── confusion_matrix_decision_tree.png
    ├── elbow_method.png
    └── cluster_visualization.png

Installation

# 1. Clone the repository
git clone https://github.com/<your-username>/customer-churn-prediction.git
cd customer-churn-prediction

# 2. (Optional) create a virtual environment
python -m venv venv
source venv/bin/activate      # Windows: venv\Scripts\activate

# 3. Install dependencies
pip install -r requirements.txt

Usage

The dataset is already included in the repo, so just launch the notebook:

jupyter notebook Customer_Churn_Prediction.ipynb

Alternatively, open it directly in Google Colab (this notebook was originally developed there) and upload Telco Customer Churn.csv when prompted.

Methodology

The project is organized into three phases, following the notebook's own structure.

Phase 1 — Data Engineering

  • Loaded the dataset and inspected data types.
  • Found that TotalCharges contained blank-string values (not true NaNs) for 11 records, all corresponding to customers with tenure = 0 — i.e., brand-new customers with no accumulated charges yet.
  • Converted TotalCharges to numeric and imputed those 11 missing values with 0, preserving their real business meaning instead of using a generic mean/median imputation.
  • Split the data into 80% train / 20% test sets (stratified by Churn) before any preprocessing, to avoid data leakage.
  • Built a ColumnTransformer pipeline: OneHotEncoder (drop-first, unknown categories ignored) for categorical features, and StandardScaler for the numerical features (tenure, MonthlyCharges, TotalCharges).

Phase 2 — Supervised Learning

Two classifiers were trained on the same processed data and compared using Accuracy, Precision, Recall, F1-Score, ROC AUC, and confusion matrices:

  • Logistic Regression
  • Decision Tree Classifier

Phase 3 — Unsupervised Learning (Customer Segmentation)

  • Applied the Elbow Method on tenure, MonthlyCharges, and TotalCharges to select the optimal number of clusters → k = 3.
  • Trained a K-Means model and profiled each resulting segment.

Results

Model Comparison

Both models reached a similar overall accuracy (~80.6%) on the test set. Since the real goal is to correctly flag customers who are about to churn — not just to classify correctly on average — the comparison below focuses on the metrics that matter most for that goal:

Metric Logistic Regression Decision Tree
Accuracy 80.62% 74.10%
Precision 65.93% 51.12%
Recall 55.88% 48.66%
F1-Score 60.49% 49.86%
ROC AUC 0.842 0.659
True Positives detected (out of 373 churners) 209 182

Logistic Regression was selected as the best model — it correctly identified 27 more churning customers than the Decision Tree and outperformed it on every discriminative metric.

Confusion Matrix - Logistic Regression Confusion Matrix - Decision Tree

Customer Segmentation (K-Means, k = 3)

Elbow Method Cluster Visualization

Cluster Avg. Tenure Avg. Monthly Charges Avg. Total Charges Profile
0 44.1 months $77.69 $3,272.60 Mid-tenure customers with above-average spend
1 18.2 months $49.75 $684.39 Newer customers on lower-cost plans
2 64.4 months $97.92 $6,292.97 Long-tenured, high-value customers

Key Insights & Business Recommendations

  • Model choice matters more than raw accuracy. Both models scored ~80% accuracy, but Logistic Regression's higher recall and ROC AUC make it far more useful for a churn-prevention use case, where missing an at-risk customer is costlier than a false alarm.
  • Data quality issues can carry business meaning. The missing TotalCharges values weren't errors — they marked brand-new customers, and treating them that way (rather than imputing a generic statistic) kept the dataset faithful to reality.
  • Segments enable targeted retention strategies:
    • Long-tenured, high-value customers (Cluster 2) are prime candidates for loyalty programs.
    • Newer customers (Cluster 1) could benefit from onboarding initiatives that increase early engagement.
    • Mid-tenure customers (Cluster 0) can be targeted with personalized upsell or retention offers.
  • Supervised + unsupervised learning together tell a fuller story: classification predicts who is likely to churn, while clustering explains what kind of customer they are — combining both supports more informed retention strategies.

Possible Next Steps

  • Address class imbalance explicitly (class_weight='balanced', SMOTE) to push recall even higher.
  • Tune hyperparameters with GridSearchCV / RandomizedSearchCV.
  • Benchmark additional models (Random Forest, Gradient Boosting / XGBoost).
  • Use k-fold cross-validation for more robust performance estimates.
  • Add feature importance / SHAP analysis to explain individual predictions.
  • Wrap the final model in a simple API or Streamlit app for interactive churn scoring.

Author

Manuel Arroyo GitHubLinkedIn

License

This project is licensed under the MIT License. See the LICENSE file for details.

About

End-to-end Machine Learning pipeline to predict telecom customer churn using Logistic Regression and Decision Trees, combined with K-Means clustering for customer segmentation.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages