Skip to main content
LearnMLAcademy
Intermediate10 min read

Customer Churn Prediction — End-to-End ML Project

Build an end-to-end customer churn prediction pipeline with scikit-learn, with reproducible setup, model evaluation, and an end-to-end project task.

What you will master in this lesson
Intuitive core mechanisms & practical real-world intuition
Step-by-step mathematical breakdown & visual diagrams
Runnable Python implementation & practical trade-offs

1. Project Goal

Build a reproducible classifier that estimates whether a subscription customer will leave during a defined future window, then turn probabilities into a retention decision whose business costs are explicit. Churn is the target event; it does not mean an unhappy customer unless the label definition says so.

2. What You Will Build

A leakage-safe preprocessing and modeling pipeline
A Logistic Regression baseline and tree-based comparison
Threshold-aware evaluation with a confusion matrix, precision, recall, F1 and ROC-AUC
A short model card covering feature influence, failure groups and monitoring

3. Skills / Prerequisites

Review unfamiliar foundations before implementing the project. Each link points to an existing lesson used by the workflow.

4. Dataset or Inputs

Use one row per customer at a fixed snapshot date. The label must look forward—for example, churned within the next 30 days—while every feature must be known at the snapshot. The inline Telco-style sample keeps the mechanics reproducible; a larger CSV should keep the same schema.

Understand every project input

Understand every project input
FieldExampleMeaning / origin
tenure_months7Completed months since signup; numeric feature
monthly_charge76Current monthly bill; missing values are imputed from training data
contractMonth-to-monthPlan category; one-hot encoded
tech_supportNoWhether support is included
churn1Target: left in the next 30 days; 0 means stayed

5. Architecture / Workflow

Split customers before learning any preprocessing values.

Fit imputers, encoders, optional scaling and the classifier only on training rows.

Return probabilities so the decision threshold can reflect retention capacity and error cost.

Evaluate once on untouched test customers and save the complete pipeline.

Project figure

From customer records to a monitored churn decision

Where is each transformation learned, and where is it applied?

Telco rows
features + churn label
Split
train 80% / test 20%
Fit preprocessing
impute + encode
Train models
logistic + tree
Evaluate
threshold + business cost
The split happens before preprocessing. The imputer, encoder, scaler and model learn only from training rows; the held-out test rows are transformed with those saved rules.

6. Environment / Dependencies

  • Python 3.10+
  • pandas and NumPy
  • scikit-learn
  • matplotlib or seaborn for optional plots

7. Data or Input Understanding

Check label rate, missingness, category values and duplicated customer IDs before modeling. A customer must appear in only one split.

Scaling is useful for Logistic Regression because coefficients are optimized across numeric features with different units. Trees split on ordered values and usually do not require scaling. One pipeline can scale numeric features for the linear baseline while the tree comparison uses an appropriate preprocessing branch.

8. Baseline / Simplest Working Approach

Begin with a majority-class rule and Logistic Regression. The majority rule reveals how misleading accuracy can be; Logistic Regression supplies probabilities and directional coefficients. Compare with a Random Forest only after the baseline is stable.

Choose a threshold on validation data, not the test set. A lower threshold flags more customers: recall usually rises, while precision and contact cost may fall.

Project figure

A threshold changes who receives retention help

Why can the same probability model produce different business outcomes?

Threshold 0.50

Predicted Stay
Predicted Churn
True Stay
4
correct
1
error
True Churn
1
error
3
correct

Threshold 0.30

Predicted Stay
Predicted Churn
True Stay
2
correct
3
error
True Churn
0
error
4
correct
At 0.50 the example finds 3 of 4 churners and contacts 4 customers. At 0.30 it finds all 4 churners but contacts 6 customers, increasing false positives and campaign cost.

Worked Example: Calculate classification metrics at threshold 0.50

Given: Nine held-out customers produce TN = 4, FP = 1, FN = 1 and TP = 3. These counts come directly from comparing each predicted class with the true churn label.

  1. 1Precision = TP / (TP + FP) = 3 / (3 + 1) = 0.75.
  2. 2Recall = TP / (TP + FN) = 3 / (3 + 1) = 0.75.
  3. 3F1 = 2 × precision × recall / (precision + recall) = 2 × 0.75 × 0.75 / 1.50 = 0.75.
  4. 4Accuracy = (TP + TN) / 9 = (3 + 4) / 9 = 0.78.

Interpretation: The model finds three quarters of churners and three quarters of contacted customers truly churn. Accuracy alone hides the missed churner and unnecessary retention contact.

9. Step-by-Step Implementation

Step 1: Create and inspect the reproducible fallback

The eight rows are deliberately tiny: they let a learner trace every value, but they are not enough for a trustworthy business model.

Create and inspect the reproducible fallbackRUNNABLE CODE
import pandas as pd

# Each row is one customer at the prediction date.
df = pd.DataFrame([
  [2, 89, "Month-to-month", "No", 1],
  [48, 55, "Two year", "Yes", 0],
  [7, 76, "Month-to-month", "No", 1],
  [36, 62, "One year", "Yes", 0],
  [1, None, "Month-to-month", "No", 1],
  [60, 45, "Two year", "Yes", 0],
  [14, 71, "One year", "No", 0],
  [5, 95, "Month-to-month", "No", 1],
], columns=["tenure_months", "monthly_charge", "contract", "tech_support", "churn"])

X = df.drop(columns="churn")
y = df["churn"]  # 1 = left within the prediction window; 0 = stayed
Representative expected output: Expected inspection: 8 rows, 4 churn labels, and one missing monthly_charge.

Step 2: Split before preprocessing

For a real dataset, stratification preserves the churn proportion. The fixed random state makes the teaching split reproducible.

Split before preprocessingRUNNABLE CODE
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.25, stratify=y, random_state=42
)

Step 3: Fit the complete baseline pipeline

The median, scaling statistics, category vocabulary and model coefficients are all learned by model.fit from X_train and y_train.

Fit the complete baseline pipelineRUNNABLE CODE
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler

numeric = ["tenure_months", "monthly_charge"]
categorical = ["contract", "tech_support"]
preprocess = ColumnTransformer([
  ("num", Pipeline([("impute", SimpleImputer(strategy="median")),
                     ("scale", StandardScaler())]), numeric),
  ("cat", OneHotEncoder(handle_unknown="ignore"), categorical),
])
model = Pipeline([("prepare", preprocess),
                  ("classifier", LogisticRegression(class_weight="balanced"))])
model.fit(X_train, y_train)
probability = model.predict_proba(X_test)[:, 1]
prediction = (probability >= 0.40).astype(int)

Step 4: Compare a tree without changing the test set

Use validation or cross-validation to compare candidates; keep the final test set for one unbiased estimate.

Compare a tree without changing the test setRUNNABLE CODE
from sklearn.ensemble import RandomForestClassifier
forest = Pipeline([("prepare", preprocess), ("classifier", RandomForestClassifier(
    n_estimators=200, class_weight="balanced", random_state=42
))])

10. Expected Results / Outputs

Read the output as evidence, not decoration

Read the output as evidence, not decoration
Model / ruleRecallPrecisionROC-AUCInterpretation
Predict everyone stays0.00undefined0.50Accuracy may look high but no churner is found
Logistic Regression0.750.750.82Transparent probability baseline
Random Forest0.790.700.85Finds more churners but contacts more non-churners

11. Evaluation

ROC-AUC measures ranking across thresholds; it does not choose the operational threshold. Inspect precision, recall and F1 at candidate thresholds and translate FP/FN counts into money or capacity.

A false negative misses a customer who leaves. A false positive spends retention effort on someone who would stay. Segment results by tenure, contract and acquisition channel to find concentrated failure.

Project figure

Feature influence explains direction, not destiny

Which signals push the churn score up or down in the fitted baseline?

Month-to-month
+2.1
High charges
+1.5
Short tenure
+1.2
Two-year plan
-1.8
Tech support
-1.0
Positive bars raise the log-odds of churn; negative bars lower them. Coefficients describe the fitted sample and should not be interpreted as causal effects.

12. Failure Analysis

Failure mode → diagnosis → response

Failure mode → diagnosis → response
Observed failureLikely causeNext action
LeakageA cancellation-date feature appears before the prediction dateRebuild features from snapshot-time data
Low churn recallThreshold too high or minority pattern underlearnedTune on validation; use class weights and better signals
Many false positivesThreshold too lowRaise threshold or limit offers by expected value
Coefficient misreadAssociation treated as causeDescribe influence, validate with domain evidence

13. Improve the Project

Add service-quality and recent-usage trends available before the snapshot.
Calibrate probabilities so 0.40 corresponds more closely to observed churn frequency.
Compare expected retention value, not only metric differences.
Audit performance and offer impact across meaningful customer groups.

14. Production Considerations

What changes beyond the notebook

What changes beyond the notebook
AreaProduction requirement
Saved artifactPreprocessor + model + threshold + feature schema
Online checkReject missing/unknown required fields; log version
MonitoringInput drift, probability drift, recall when labels arrive, offer uptake
RetrainingTime-based schedule or performance trigger; revalidate threshold

15. Summary / Key Takeaways

  • Churn must be defined as a future target relative to a clear customer snapshot.
  • Splitting before preprocessing prevents test information from influencing imputation, encoding and scaling.
  • A majority rule and Logistic Regression establish honest baselines before a tree comparison.
  • Precision, recall and F1 describe different consequences hidden by accuracy.
  • ROC-AUC evaluates ranking, while a validation-chosen threshold controls the actual retention action.
  • Feature influence explains the fitted model but does not prove that a feature causes churn.
  • A production churn system saves its schema, preprocessing, model and threshold and monitors both drift and business outcomes.

Apply this concept in a real hands-on project

You have studied the idea. Now use it in working Python code, see the calculation and output, and explain what changed. Each project includes step-by-step instructions, full source and tests.

Practice challenge: predict an outcome first, run the code, and explain the difference.

Track Your Progress0% curriculum done

Finished "Customer Churn Prediction — End-to-End ML Project"?

Mark this lesson as completed to update your progress bar and track your milestones across the full curriculum.

Overall Progress0 / 167 lessons

Was this tutorial helpful?

Your feedback helps us continuously refine and improve our open-access tutorials.

Knowledge Check

Progress: 0/5

Test your active recall. Choose one answer for each question, then check it to reveal the step-by-step reasoning.

Question 1 of 5interpretation
A churn dataset is 90% non-churn. A model predicts every customer will stay and reports 90% accuracy. What is the main problem?
Question 2 of 5practical selection
When should the imputer's median be learned?
Question 3 of 5numerical/formula
At a threshold, TP=6 and FP=2. What is churn precision?
Question 4 of 5application/scenario
What usually happens when the churn threshold is lowered from 0.50 to 0.30?
Question 5 of 5debugging/diagnostic
Production churn recall falls only for new month-to-month customers. What should be investigated first?

Knowledge Check Review & Explanations

Review the questions, verified correct answers, and conceptual explanations for this lesson.

1A churn dataset is 90% non-churn. A model predicts every customer will stay and reports 90% accuracy. What is the main problem?▼

Correct Answer: It finds no churners, so churn recall is zero

The majority shortcut can look accurate while missing every positive churn case. The confusion matrix and recall reveal this failure.

2When should the imputer's median be learned?▼

Correct Answer: From training rows, then reused on validation and test

Learning the median from held-out rows leaks information. Fit preprocessing on training data and reuse the learned value elsewhere.

3At a threshold, TP=6 and FP=2. What is churn precision?▼

Correct Answer: 0.75

Precision = TP/(TP+FP) = 6/(6+2) = 0.75. Three quarters of flagged customers truly churned.

4What usually happens when the churn threshold is lowered from 0.50 to 0.30?▼

Correct Answer: Recall can rise while false positives also rise

Lowering the threshold changes the decision rule, not model weights. It flags more customers, often finding more churners and more non-churners.

5Production churn recall falls only for new month-to-month customers. What should be investigated first?▼

Correct Answer: Segment-specific data drift and recent labels

A concentrated failure suggests segment drift or missing signals. Inspect that group before changing the entire model.

Keep moving through the path

Continue Learning

Free Download: ML Interview Cheatsheet

100 essential Machine Learning interview questions and answers covering foundations, algorithms, evaluation, deep learning, Python, system design and interview strategy. Enter your email to download it instantly.

Next