← All articlesData Science

Customer Churn Prediction in Python: An End-to-End Project from Raw Data to Retention Plan

By Skillancy Editorial Team · 29 November 2026 · 27 min read

Reviewed by Rishav Kumar, Principal Data Analyst, Walmart Global Tech

Skillancy cover: Customer Churn Prediction in Python, end to end with EDA, leakage, XGBoost, SHAP and a threshold set in rupees. For a 100 rupee retention offer on 4,000 customers, offering to everyone lost 1.07 lakh rupees, the model at the default 0.5 threshold made 16,000 and the best threshold of 0.23 made 51,000

Customer churn prediction means using a customer's recent behaviour to estimate how likely they are to leave, so a business can try to keep them before they go. It's one of the most common machine learning projects in Indian companies: telecom operators watch for prepaid users about to port out, food delivery apps watch for users who stop ordering, and fintech apps watch for wallets going quiet. This post builds a complete churn prediction project in Python, from a raw CSV to a retention plan with a rupee value. It covers cleaning, EDA, the leakage trap, a logistic regression baseline, XGBoost, imbalanced data, a profit-based threshold, SHAP explanations and a lift table. Every number shown comes from running the code, so you can reproduce it in Google Colab and put it in your portfolio.

QuestionShort answer
What is customer churn?A customer stopping use of a product or service: a prepaid SIM not recharged, an app user who stops ordering, a cancelled subscription
Which algorithm is best for churn prediction?Start with logistic regression as a baseline, then try gradient boosting (XGBoost, LightGBM). In this project XGBoost beat the baseline only slightly, on PR-AUC 0.404 vs 0.380
Which metric should I use?PR-AUC, plus precision and recall at your chosen threshold. Accuracy misleads when only about 18% of customers churn
How do I handle class imbalance?Use stratified splits and imbalance-aware metrics, then pick the threshold by business cost. scale_pos_weight raises recall but distorts probabilities
How do I explain the model to a manager?SHAP values: which features pushed this customer's risk up or down, and by how much
Is this a good portfolio project?Yes, if you show the business decision (who gets the offer and the rupee impact), not just a model score
Data note: the dataset in this post is synthetic. It's generated by the code below to look like an Indian prepaid telecom base (telecom circles, ARPU in rupees, dual-SIM users, days without an active pack). It's not real company data, so the exact numbers describe this simulation, not any operator. The workflow is the same one you'd use on real data.

New to pandas? The free Python tutorial has short lessons on data cleaning, groupby, distributions and outliers and regression basics that cover every building block used here.

What is customer churn prediction?

Churn is when a customer stops being a customer. Churn prediction is a classification problem: for each customer who is active today, predict the probability that they churn in a future window, using only what you know today.

Three words in that sentence do a lot of work:

  • Active today. You only score customers you can still save. Customers who already left aren't in the scoring set.
  • Future window. "Will churn" has to mean something precise, such as "no recharge in the next 60 days".
  • Know today. Features must be measured on or before the cutoff date. Anything measured later leaks the answer (Step 4 shows how badly).

Why companies care

Keeping a customer is usually cheaper than winning a new one, and churn compounds: a telecom operator that loses 2% of its prepaid base every month loses about 22% of it in a year. But a retention offer costs money. A churn model is useful only if it helps decide who gets the offer, so that the money spent saving customers is less than the revenue saved. That's why this project ends with a rupee number, not an accuracy score.

How churn is defined in different Indian businesses

BusinessTypical churn definitionContract type
Prepaid telecomNo recharge within N days after the pack expires, or a port-out requestNon-contractual: customers leave silently
Postpaid telecom, OTT, SaaSSubscription cancelled or not renewedContractual: you see the exit
Food delivery, quick commerceNo order in 30 to 60 days for a previously regular customerNon-contractual
Banking and fintechAccount or wallet inactive for 90+ days, or balance moved outMixed

Non-contractual churn (prepaid, food delivery) is harder: nobody tells you they've left, so you have to define the label yourself. Write the definition down before you write any code, because every later step depends on it.

The project workflow

Churn prediction workflow in six steps: define churn, clean and explore, remove leakage, train baseline and XGBoost, evaluate on imbalanced data, then pick a profit threshold and explain with SHAP

The timeline matters as much as the model. Features come from the observation window before the cutoff date (here, the last 90 days). The label comes from the churn window after it (the next 60 days). Nothing from the churn window may appear in the features.

Step 1: Build the dataset

The script generates 20,000 synthetic prepaid subscribers. Churn is driven by short tenure, complaint calls, call drops (worse in some circles), plan downgrades, days without an active pack and dual-SIM use. UPI autopay and heavier data use reduce it. Some ARPU and data values are missing, and 60 hotspot users have extreme data usage, as real extracts do. It also adds one leaky column on purpose.

Install the packages once (Colab already has most of them):

pip install pandas numpy scikit-learn xgboost shap matplotlib
import numpy as np
import pandas as pd

rng = np.random.default_rng(42)
n = 20_000

circles = ["Mumbai", "Delhi NCR", "Karnataka", "Tamil Nadu", "Maharashtra",
           "Gujarat", "UP East", "Bihar", "West Bengal", "Kerala"]
circle = rng.choice(circles, n, p=[.12, .14, .11, .10, .11, .09, .11, .08, .08, .06])
circle_risk = {"Mumbai": 0.0, "Delhi NCR": 0.05, "Karnataka": -0.05, "Tamil Nadu": -0.1,
               "Maharashtra": 0.0, "Gujarat": -0.05, "UP East": 0.3, "Bihar": 0.35,
               "West Bengal": 0.1, "Kerala": -0.15}
circle_drops = {"UP East": 1.0, "Bihar": 1.2, "West Bengal": 0.4}  # extra call-drop %

tenure = np.clip(rng.gamma(1.6, 18, n).round().astype(int) + 1, 1, 120)
arpu = np.clip(rng.lognormal(np.log(260), 0.35, n), 99, 1200).round()
data_gb = np.clip(rng.gamma(2.2, 9, n), 0.1, None).round(1)
heavy = rng.choice(n, 60, replace=False)              # hotspot users: real but extreme
data_gb[heavy] = rng.uniform(250, 900, 60).round(1)
call_drop_pct = np.clip(rng.gamma(2.0, 0.9, n) + pd.Series(circle).map(circle_drops).fillna(0).to_numpy(), 0, 15).round(2)
complaints = rng.poisson(0.35 + 0.18 * call_drop_pct)
downgrades = rng.poisson(0.25, n)
days_without_pack = np.clip(rng.gamma(1.2, 3.0, n).round(), 0, 45).astype(int)
dual_sim = rng.random(n) < 0.45
autopay = rng.random(n) < np.clip(0.10 + tenure / 300, 0, 0.6)

logit = (
    0.9 * (tenure < 6) + 0.4 * ((tenure >= 6) & (tenure < 12)) - 0.006 * tenure
    + 0.30 * complaints + 0.12 * call_drop_pct
    + 0.35 * complaints * (call_drop_pct > 3)            # complaints hurt more on a bad network
    + 0.55 * downgrades + 0.07 * days_without_pack
    + 0.5 * dual_sim - 0.9 * autopay
    - 0.015 * np.minimum(data_gb, 60)
    + pd.Series(circle).map(circle_risk).to_numpy()
    + rng.normal(0, 0.5, n)
)
lo, hi = -10.0, 5.0                                      # pick the intercept for an ~18% churn rate
for _ in range(60):
    mid = (lo + hi) / 2
    lo, hi = (mid, hi) if (1 / (1 + np.exp(-(logit + mid)))).mean() < 0.18 else (lo, mid)
churned = rng.random(n) < 1 / (1 + np.exp(-(logit + mid)))

# A column pulled at extraction time, 60 days AFTER the cutoff. It leaks the answer.
days_since_last_recharge = np.where(churned, rng.integers(40, 150, n), rng.integers(0, 45, n))

df = pd.DataFrame({
    "customer_id": [f"C{i:05d}" for i in range(n)],
    "circle": circle,
    "tenure_months": tenure,
    "arpu_rs": arpu,
    "data_gb_month": data_gb,
    "call_drop_pct": call_drop_pct,
    "complaint_calls_90d": complaints,
    "plan_downgrades_90d": downgrades,
    "days_without_pack_90d": days_without_pack,
    "dual_sim": dual_sim.astype(int),
    "upi_autopay": autopay.astype(int),
    "days_since_last_recharge": days_since_last_recharge,
    "churned": churned.astype(int),
})
df.loc[rng.choice(n, 600, replace=False), "arpu_rs"] = np.nan       # billing sync gaps
df.loc[rng.choice(n, 400, replace=False), "data_gb_month"] = np.nan

import os
os.makedirs("data", exist_ok=True)
os.makedirs("charts", exist_ok=True)
df.to_csv("data/prepaid_churn.csv", index=False)
print(df.shape)
print(df.head(3).T)

Output:

(20000, 13)
                                0           1       2
customer_id                C00000      C00001  C00002
circle                    UP East  Tamil Nadu   Bihar
tenure_months                  34          95      26
arpu_rs                     280.0       236.0   238.0
data_gb_month                19.6         3.1    25.4
call_drop_pct                2.88        0.34    4.62
complaint_calls_90d             1           0       3
plan_downgrades_90d             1           0       0
days_without_pack_90d           2           5       0
dual_sim                        1           0       0
upi_autopay                     0           1       0
days_since_last_recharge       29          23     140
churned                         0           0       1

Each row is one subscriber at the cutoff date. churned is the label: 1 if the subscriber didn't recharge in the 60 days after the cutoff.

Step 2: Clean the data

Before any chart or model, check missing values, the churn rate and outliers.

df = pd.read_csv("data/prepaid_churn.csv")
print(df.isna().sum()[lambda s: s > 0])
print(f"Churn rate: {df['churned'].mean():.1%}")

q1, q3 = df["data_gb_month"].quantile([0.25, 0.75])
upper = q3 + 1.5 * (q3 - q1)
print(f"data_gb_month IQR upper fence: {upper:.1f} GB, rows above: {(df['data_gb_month'] > upper).sum()}")
print(df["data_gb_month"].describe().round(1))

df["arpu_missing"] = df["arpu_rs"].isna().astype(int)
df["arpu_rs"] = df["arpu_rs"].fillna(df["arpu_rs"].median())
df["data_gb_month"] = df["data_gb_month"].fillna(df["data_gb_month"].median())
df["data_gb_capped"] = df["data_gb_month"].clip(upper=df["data_gb_month"].quantile(0.99))
print(f"Cap at 99th percentile: {df['data_gb_month'].quantile(0.99):.1f} GB")
arpu_rs          600
data_gb_month    400
dtype: int64
Churn rate: 18.2%
data_gb_month IQR upper fence: 51.7 GB, rows above: 632
count    19600.0
mean        21.4
std         34.3
min          0.2
25%          9.9
50%         16.9
75%         26.6
max        896.8
Name: data_gb_month, dtype: float64
Cap at 99th percentile: 67.3 GB

Three decisions, and why:

  • Missing ARPU (600 rows): fill with the median, but keep an arpu_missing flag. Missingness itself can carry signal, for example a billing problem.
  • Outliers in data usage: the IQR rule flags 632 rows, far more than the 60 true hotspot users, because usage is naturally right-skewed. Deleting 632 real customers would be wrong. Capping at the 99th percentile (67.3 GB) keeps everyone and stops a few 900 GB users from distorting a linear model.
  • Churn rate 18.2%: the classes are imbalanced. Remember this number; it comes back in Step 7.

One shortcut here deserves a warning: the medians and the 99th percentile are computed on the full dataset before the train/test split. That leaks a tiny amount of test information. It's harmless at this size, but in production put the imputation inside a scikit-learn Pipeline so it's learned from training data only (Step 5 does this for scaling).

Step 3: Explore who churns

EDA answers the analyst's question before the data scientist's: which customers leave, and what do they have in common?

df["tenure_band"] = pd.cut(df["tenure_months"], [0, 6, 12, 24, 48, 120],
                           labels=["0-6", "7-12", "13-24", "25-48", "49+"])
print(df.groupby("tenure_band", observed=True)["churned"].agg(["mean", "size"]).round(3))
print(df.groupby("circle")["churned"].mean().sort_values(ascending=False).round(3))
df["complaint_band"] = df["complaint_calls_90d"].clip(upper=4).astype(str).replace({"4": "4+"})
print(df.groupby("complaint_band")["churned"].agg(["mean", "size"]).round(3))
print(df.groupby("upi_autopay")["churned"].mean().round(3))
print(df.groupby("dual_sim")["churned"].mean().round(3))
bad_net = df["call_drop_pct"] > 3
print(df.groupby([bad_net.rename("drop_gt_3pct"), df["complaint_calls_90d"].clip(upper=3)])["churned"].mean().unstack().round(3))
              mean  size
tenure_band
0-6          0.311  1802
7-12         0.234  2947
13-24        0.168  5473
25-48        0.160  6341
49+          0.130  3437

circle
Bihar          0.267
UP East        0.228
West Bengal    0.191
Delhi NCR      0.173
...
Kerala         0.149

                 mean   size
complaint_band
0               0.138  10034
1               0.192   6710
2               0.261   2439
3               0.368    627
4+              0.511    190

upi_autopay
0    0.201
1    0.102

dual_sim
0    0.150
1    0.221

complaint_calls_90d      0      1      2      3
drop_gt_3pct
False                0.133  0.170  0.202  0.264
True                 0.170  0.268  0.388  0.566

Churn rate by tenure band, complaint calls and UPI autopay: new customers churn at 31% against 13% for 49+ months, 4+ complaints churn at 51% against 14% with none, and autopay users churn at 10% against 20%

What an analyst would tell the business from this alone:

1. New customers are fragile. Customers in their first 6 months churn at 31.1%, against 13.0% after four years. Onboarding is a retention lever.

2. Complaints are an early warning. Churn rises from 13.8% with no complaint calls to 51.1% with four or more.

3. Complaints plus a bad network is the danger zone. With call drops above 3%, three complaint calls mean 56.6% churn, against 26.4% on a good network. That's an interaction: the two together are worse than each alone. Tree models like XGBoost pick this up automatically; logistic regression doesn't unless you add the interaction yourself.

4. Autopay halves churn (10.2% vs 20.1%). Pushing UPI autopay is a cheap retention action.

5. Bihar and UP East churn most (26.7% and 22.8%), partly because their call-drop rates are higher in this simulation.

If you're on the analytics track, this is a complete deliverable: segments, rates and actions. The rest of the post is the data science track: turning these patterns into a score for every customer.

Correlation isn't causation. Autopay users churn less, but that might be because loyal users choose autopay, not because autopay creates loyalty. Test it with an experiment before claiming impact. See correlation vs causation.

Step 4: The leakage trap

days_since_last_recharge looks like a great feature. It isn't: it was pulled on extraction day, 60 days after the cutoff, so for churners it's large by definition. Watch what happens:

from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score

leaky = df[["tenure_months", "complaint_calls_90d", "days_since_last_recharge"]]
Xa, Xb, ya, yb = train_test_split(leaky, df["churned"], test_size=0.2, stratify=df["churned"], random_state=42)
leak_model = LogisticRegression(max_iter=1000).fit(Xa, ya)
print(f"ROC-AUC WITH days_since_last_recharge: {roc_auc_score(yb, leak_model.predict_proba(Xb)[:, 1]):.3f}")
ROC-AUC WITH days_since_last_recharge: 0.997

A near-perfect score from three columns. In production this model would be useless, because on the day you need a prediction the "future" recharge gap doesn't exist yet. The honest models below score around 0.72.

Rule of thumb: if a churn model scores above about 0.95, assume leakage until you prove otherwise. For every feature, ask "would I know this value on the cutoff date?" Common leaks in Indian telecom and app data include port-out request flags, "last active date" pulled at extraction time, retention-team call notes, and refund or cancellation fields.

Step 5: A logistic regression baseline

Always start with a simple, explainable model. It sets the bar a complex model must clear, and its coefficients are easy to discuss in an interview.

from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler

numeric = ["tenure_months", "arpu_rs", "data_gb_capped", "call_drop_pct", "complaint_calls_90d",
           "plan_downgrades_90d", "days_without_pack_90d", "dual_sim", "upi_autopay", "arpu_missing"]
categorical = ["circle"]
X = df[numeric + categorical]
y = df["churned"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, stratify=y, random_state=42)
print(f"Train {X_train.shape}, test {X_test.shape}, test churn rate {y_test.mean():.1%}")

pre = ColumnTransformer([("num", StandardScaler(), numeric),
                         ("cat", OneHotEncoder(drop="first"), categorical)])
logreg = Pipeline([("pre", pre), ("model", LogisticRegression(max_iter=1000))])
logreg.fit(X_train, y_train)
p_lr = logreg.predict_proba(X_test)[:, 1]
print(f"Logistic regression ROC-AUC: {roc_auc_score(y_test, p_lr):.3f}")

names = logreg.named_steps["pre"].get_feature_names_out()
coefs = pd.Series(logreg.named_steps["model"].coef_[0], index=names)
odds = np.exp(coefs).sort_values(ascending=False)
print(odds.round(2).head(6))
print(odds.round(2).tail(4))
Train (16000, 11), test (4000, 11), test churn rate 18.1%
Logistic regression ROC-AUC: 0.718
num__complaint_calls_90d      1.37
num__call_drop_pct            1.32
num__plan_downgrades_90d      1.29
num__dual_sim                 1.29
num__days_without_pack_90d    1.23
num__arpu_missing             1.03
cat__circle_Tamil Nadu    0.73
cat__circle_Karnataka     0.72
cat__circle_Gujarat       0.72
cat__circle_Kerala        0.64

How to read it:

  • stratify=y keeps the churn rate the same (18.1%) in the train and test sets. Always stratify for imbalanced labels.
  • Numeric features are standardised, so each odds ratio is per one standard deviation. One standard deviation more complaint calls multiplies the odds of churn by 1.37.
  • Circles are compared with the dropped reference category, Bihar. A Kerala customer has 0.64 times the churn odds of an otherwise identical Bihar customer.
  • ROC-AUC 0.718 is realistic for churn. Real churn models often land between 0.70 and 0.85, because people leave for reasons no dataset captures (a friend's new SIM, a move to another city).

Step 6: XGBoost, cross-validation and class imbalance

Gradient boosting builds many small decision trees, each correcting the previous ones' errors. It handles interactions (complaints × bad network) and non-linear effects (the tenure cliff) without manual feature engineering. We tune two settings with 5-fold stratified cross-validation, scored on PR-AUC.

from xgboost import XGBClassifier
from sklearn.model_selection import StratifiedKFold, GridSearchCV, cross_val_score

X_train_x = pd.get_dummies(X_train, columns=["circle"], dtype=int)
X_test_x = pd.get_dummies(X_test, columns=["circle"], dtype=int)
spw = (y_train == 0).sum() / (y_train == 1).sum()
print(f"scale_pos_weight = {spw:.2f}")

cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
grid = GridSearchCV(
    XGBClassifier(n_estimators=300, subsample=0.8, colsample_bytree=0.8,
                  eval_metric="logloss", random_state=42, n_jobs=4),
    {"max_depth": [3, 4, 6], "learning_rate": [0.03, 0.1]},
    scoring="average_precision", cv=cv)
grid.fit(X_train_x, y_train)
print("Best params:", grid.best_params_, f"CV PR-AUC {grid.best_score_:.3f}")
cv_lr = cross_val_score(logreg, X_train, y_train, cv=cv, scoring="average_precision")
print(f"Logistic regression CV PR-AUC {cv_lr.mean():.3f} (+/- {cv_lr.std():.3f})")

xgb = grid.best_estimator_                       # unweighted: probabilities stay honest
xgb_w = XGBClassifier(**{**xgb.get_params(), "scale_pos_weight": spw}).fit(X_train_x, y_train)
p_xgb = xgb.predict_proba(X_test_x)[:, 1]
p_xgb_w = xgb_w.predict_proba(X_test_x)[:, 1]
print(f"Mean predicted churn: unweighted {p_xgb.mean():.3f}, weighted {p_xgb_w.mean():.3f}, actual {y_test.mean():.3f}")
scale_pos_weight = 4.51
Best params: {'learning_rate': 0.03, 'max_depth': 3} CV PR-AUC 0.376
Logistic regression CV PR-AUC 0.371 (+/- 0.016)
Mean predicted churn: unweighted 0.181, weighted 0.450, actual 0.181

Two lessons that tutorials usually skip:

1. XGBoost barely beat the baseline in cross-validation: PR-AUC 0.376 vs 0.371, inside the baseline's ±0.016 spread. The strongest signals here are simple and close to linear, so a fancier algorithm adds little. On real projects better features (a recharge trend, network quality at the customer's tower) usually beat a better algorithm. Report this honestly; interviewers respect it.

2. scale_pos_weight distorts probabilities. It tells XGBoost to treat each churner as 4.51 customers. The weighted model predicts an average churn risk of 45.0% when the true rate is 18.1%. That's fine for ranking, but wrong if you multiply probabilities by rupees, which is exactly what Step 8 does. So we keep the unweighted model for decisions and handle imbalance with the threshold instead.

Step 7: Evaluate on imbalanced data

from sklearn.metrics import (accuracy_score, average_precision_score, confusion_matrix,
                             precision_score, recall_score)
from sklearn.dummy import DummyClassifier

dummy = DummyClassifier(strategy="most_frequent").fit(X_train, y_train)
print(f"'Nobody churns' accuracy: {accuracy_score(y_test, dummy.predict(X_test)):.3f}")
rows = []
for name, p in [("Logistic regression", p_lr), ("XGBoost", p_xgb), ("XGBoost + scale_pos_weight", p_xgb_w)]:
    pred = (p >= 0.5).astype(int)
    rows.append({"model": name, "accuracy": accuracy_score(y_test, pred),
                 "precision": precision_score(y_test, pred), "recall": recall_score(y_test, pred),
                 "roc_auc": roc_auc_score(y_test, p), "pr_auc": average_precision_score(y_test, p)})
print(pd.DataFrame(rows).round(3).to_string(index=False))
print(confusion_matrix(y_test, (p_xgb >= 0.5).astype(int)))
'Nobody churns' accuracy: 0.819
                     model  accuracy  precision  recall  roc_auc  pr_auc
       Logistic regression     0.825      0.676   0.069    0.718   0.380
                   XGBoost     0.825      0.634   0.088    0.725   0.404
XGBoost + scale_pos_weight     0.676      0.308   0.631    0.722   0.400
[[3237   37]
 [ 662   64]]

This table is the most important one in the post:

  • Accuracy is useless here. Predicting that nobody churns scores 81.9%. Both real models score 82.5%, almost the same, yet XGBoost at 0.5 misses 662 of 726 churners (recall 8.8%).
  • The 0.5 threshold is arbitrary. With an 18% base rate, few customers ever reach a 50% churn probability, so very few get flagged. Weighting the classes moves recall from 8.8% to 63.1%, but precision drops from 63.4% to 30.8%. Neither is "right" until you know what a false alarm and a missed churner cost.
  • PR-AUC is the honest summary. It measures how well the model ranks churners above non-churners where it matters, at the top of the list. A random model would score about 0.18 (the churn rate); XGBoost scores 0.404.
MetricAnswersUse it when
AccuracyWhat share of all predictions is right?Classes are balanced. Not for churn
PrecisionOf customers we flagged, how many really churn?Each offer is expensive
RecallOf real churners, how many did we flag?Missing a churner is expensive
ROC-AUCHow well does the model rank a random churner above a random stayer?Comparing models; it can look good even when the top of the list is weak
PR-AUCRanking quality focused on the rare classImbalanced data such as churn and fraud

Step 8: Choose the threshold with rupees, not 0.5

Now turn probabilities into a business decision. Assume a retention offer (say a 5 GB data voucher plus the cost of sending it) costs ₹100, keeps 30% of real churners who receive it, and a saved customer is worth 12 months of ARPU at a 40% margin. For a ₹260 ARPU customer, that's ₹1,248.

OFFER_COST = 100         # e.g. a 5 GB data voucher plus SMS and call-centre cost, in rupees
SAVE_RATE = 0.30         # share of real churners the offer keeps
MARGIN = 0.40            # margin on ARPU
MONTHS = 12              # months of revenue a saved customer is worth
value = X_test["arpu_rs"].to_numpy() * MARGIN * MONTHS

def campaign_profit(p, threshold):
    target = p >= threshold
    saved = (target & (y_test.to_numpy() == 1)) * SAVE_RATE * value
    return saved.sum() - target.sum() * OFFER_COST, target.sum()

thresholds = np.round(np.arange(0.05, 0.96, 0.01), 2)
curve = pd.DataFrame([(t, *campaign_profit(p_xgb, t)) for t in thresholds],
                     columns=["threshold", "profit_rs", "customers_targeted"])
best = curve.loc[curve["profit_rs"].idxmax()]
at_half = curve.loc[curve["threshold"] == 0.5].iloc[0]
everyone = campaign_profit(p_xgb, 0.0)
print(f"Target everyone: profit Rs {everyone[0]:,.0f} on {everyone[1]} customers")
print(f"Threshold 0.50: profit Rs {at_half.profit_rs:,.0f} on {int(at_half.customers_targeted)} customers")
print(f"Best threshold {best.threshold:.2f}: profit Rs {best.profit_rs:,.0f} on {int(best.customers_targeted)} customers")
pred_best = (p_xgb >= best.threshold).astype(int)
print(f"At best threshold: precision {precision_score(y_test, pred_best):.3f}, recall {recall_score(y_test, pred_best):.3f}")
Target everyone: profit Rs -107,003 on 4000 customers
Threshold 0.50: profit Rs 16,346 on 101 customers
Best threshold 0.23: profit Rs 50,861 on 974 customers
At best threshold: precision 0.376, recall 0.504

Campaign profit against the churn-probability threshold: profit is negative below about 0.12, peaks at threshold 0.23 and falls toward zero as the threshold rises, with the 0.5 default well past the peak

StrategyCustomers offeredProfit on 4,000 test customers
Offer to everyone (no model)4,000−₹1,07,003
Model at the default 0.5 threshold101₹16,346
Model at the profit-optimal 0.23 threshold974₹50,861

The model is worth money only once you pick the threshold with the business numbers. At 0.23 it flags about a quarter of customers, catches half of all churners (recall 50.4%), and 37.6% of the people it flags really were going to leave, about double the 18% base rate.

Two cautions:

  • The best threshold moves with the costs. A cheaper offer pushes it down and a pricier one pushes it up. Re-run the curve when the offer changes, and show the curve, not just one number.
  • "Saves 30% of churners" is an assumption. Measure it with a holdout group: randomly withhold the offer from some high-risk customers and compare their churn. That's an A/B test, and it's the only way to know the campaign works.

Step 9: Explain the model with SHAP

A retention manager won't act on "XGBoost said 0.91". SHAP values split each prediction into contributions from each feature: how much each one pushed this customer's risk up or down from the average.

import shap
import matplotlib.pyplot as plt

explainer = shap.TreeExplainer(xgb)
sv = explainer(X_test_x)
mean_abs = pd.Series(np.abs(sv.values).mean(axis=0), index=X_test_x.columns).sort_values(ascending=False)
print(mean_abs.round(3).head(8))

shap.plots.beeswarm(sv, max_display=10, show=False)
plt.savefig("charts/churn-shap-beeswarm.png", dpi=150, bbox_inches="tight")
plt.close()

i = int(np.argmax(p_xgb))
row = X_test_x.iloc[i]
contrib = pd.Series(sv.values[i], index=X_test_x.columns).sort_values(key=abs, ascending=False)
print(f"Highest-risk customer {df.loc[X_test.index[i], 'customer_id']}: p = {p_xgb[i]:.3f}, base value {sv.base_values[i]:.3f}")
for feat, val in contrib.head(5).items():
    print(f"  {feat} = {row[feat]}  ->  {val:+.3f}")
tenure_months            0.241
dual_sim                 0.227
call_drop_pct            0.224
complaint_calls_90d      0.219
upi_autopay              0.194
plan_downgrades_90d      0.191
days_without_pack_90d    0.135
data_gb_capped           0.130

Highest-risk customer C19282: p = 0.910, base value -1.508
  call_drop_pct = 8.06  ->  +1.176
  complaint_calls_90d = 3.0  ->  +0.792
  plan_downgrades_90d = 2.0  ->  +0.782
  tenure_months = 3.0  ->  +0.708
  upi_autopay = 1.0  ->  -0.349

SHAP beeswarm for the XGBoost churn model: short tenure, dual SIM, high call drops, complaint calls, no autopay and plan downgrades push churn risk up; long tenure and autopay push it down

How to read the beeswarm: each dot is a test customer. Red means a high feature value, blue a low one. Dots to the right raise churn risk. Low tenure (blue) sits on the right, so new customers are riskier. Autopay = 1 (red) sits on the left, so autopay lowers risk.

For one customer, SHAP values are in log-odds and add up. The average customer starts at −1.508 (about an 18% probability). Customer C19282's 8% call-drop rate adds +1.18, three complaint calls add +0.79, two downgrades add +0.78 and a 3-month tenure adds +0.71. Autopay takes off 0.35. Together with the smaller features, the total lands at a 91% churn risk.

The sentence for the retention manager: "C19282 joined 3 months ago, has had an 8% call-drop rate, called us 3 times to complain and has downgraded twice. The network is the problem. Send a network-team callback, not a discount."

That's the real value of SHAP: it changes which action you take, not just whom you target. Two cautions: SHAP explains what the model learned, not what causes churn in the real world, and correlated features can share or swap credit.

Step 10: From scores to a retention plan

Most retention teams work with a budget, not a threshold: "we can call 800 customers this month". A lift table sorts customers by risk and shows how many churners each tenth of the list contains.

scored = pd.DataFrame({"p": p_xgb, "churned": y_test.to_numpy()})
scored["decile"] = pd.qcut(scored["p"].rank(method="first", ascending=False), 10, labels=range(1, 11))
lift = scored.groupby("decile", observed=True).agg(customers=("p", "size"), churners=("churned", "sum"),
                                                   avg_score=("p", "mean"))
lift["churn_rate"] = lift["churners"] / lift["customers"]
lift["cum_share_of_churners"] = lift["churners"].cumsum() / lift["churners"].sum()
lift["lift"] = lift["churn_rate"] / scored["churned"].mean()
print(lift.round(3).to_string())
        customers  churners  avg_score  churn_rate  cum_share_of_churners   lift
decile
1             400       189      0.449       0.472                  0.260  2.603
2             400       128      0.287       0.320                  0.437  1.763
3             400        90      0.228       0.225                  0.561  1.240
4             400        75      0.190       0.188                  0.664  1.033
5             400        64      0.160       0.160                  0.752  0.882
6             400        54      0.138       0.135                  0.826  0.744
7             400        46      0.119       0.115                  0.890  0.634
8             400        35      0.100       0.088                  0.938  0.482
9             400        26      0.081       0.065                  0.974  0.358
10            400        19      0.054       0.048                  1.000  0.262
  • The top 10% of scores holds 26.0% of all churners, with a churn rate of 47.2%: 2.6 times the average.
  • The top 20% holds 43.7% of churners. If the team can only call 800 of 4,000 customers, the model finds 317 churners in those 800 calls. Random calling would find about 145.
  • The bottom decile churns at only 4.8%. Don't spend money there.

A simple plan built from this table:

SegmentAction
Decile 1, network-driven risk (SHAP shows call drops or complaints)Network-team callback and a complaint follow-up
Decile 1–2, price-driven risk (downgrades, days without a pack)Personalised recharge offer
Decile 1–3, new customersOnboarding nudge and a UPI autopay incentive
Deciles 4–10No paid offer; normal communication

Scoring new customers

Wrap the preparation and the model in one function so next month's extract is scored exactly the way training data was:

def score_customers(new_df):
    """Score a fresh extract the same way the model was trained."""
    d = new_df.copy()
    d["arpu_missing"] = d["arpu_rs"].isna().astype(int)
    d["arpu_rs"] = d["arpu_rs"].fillna(df["arpu_rs"].median())
    d["data_gb_capped"] = d["data_gb_month"].fillna(df["data_gb_month"].median()).clip(upper=df["data_gb_month"].quantile(0.99))
    Xn = pd.get_dummies(d[numeric + categorical], columns=["circle"], dtype=int)
    Xn = Xn.reindex(columns=X_train_x.columns, fill_value=0)
    d["churn_risk"] = xgb.predict_proba(Xn)[:, 1]
    d["send_offer"] = d["churn_risk"] >= best.threshold
    return d[["customer_id", "churn_risk", "send_offer"]].sort_values("churn_risk", ascending=False)

raw = pd.read_csv("data/prepaid_churn.csv").drop(columns=["churned", "days_since_last_recharge"])
print(score_customers(raw.sample(5, random_state=7)).round(3).to_string(index=False))
customer_id  churn_risk  send_offer
     C12153       0.438        True
     C03439       0.354        True
     C18549       0.146       False
     C14356       0.141       False
     C15029       0.050       False

reindex(columns=...) matters: if next month's file has no Kerala customers, get_dummies won't create a circle_Kerala column and the model would fail or, worse, misread the columns. Reindexing forces the exact training layout. (These five rows were also in the training data. Use them to check the function, not the model.)

To share it, save the model with joblib.dump(xgb, "churn_model.joblib") and wrap score_customers in a small FastAPI endpoint or a Streamlit page that accepts a CSV upload. Both are covered in the deployment modules of our programs.

Monitoring after launch

A churn model decays. Plans change, a competitor launches a cheap pack, a new tower fixes call drops. Check monthly:

  • Score drift: has the share of customers above the threshold jumped?
  • Feature drift: have average call drops or complaint calls moved?
  • Outcome check: 60 days later, did the flagged customers churn at the rate the model expected? Recompute precision, recall and PR-AUC on the new labels.
  • Campaign effect: compare churn in treated vs holdout high-risk customers. That's the number the business cares about.

Churn prediction interview questions

If this project is on your resume, expect these questions.

1. How did you define churn, and why? "No recharge in the 60 days after the cutoff. Prepaid is non-contractual, so I picked a window longer than the usual pack validity to avoid counting late recharges as churn."

2. How did you prevent data leakage? "Every feature is measured on or before the cutoff. I dropped days_since_last_recharge because it was pulled at extraction time; with it, ROC-AUC jumped to 0.997."

3. Your classes are imbalanced. What did you do? "Stratified splits and cross-validation, PR-AUC as the main metric, and a threshold chosen by profit. I tried scale_pos_weight, but it inflated the average predicted risk from 18% to 45%, so I didn't use it for rupee decisions."

4. Why not accuracy? "Predicting that nobody churns gives 81.9% accuracy and catches zero churners."

5. Why XGBoost over logistic regression? "It captures interactions like complaints on a bad network. But here it beat the baseline only slightly (CV PR-AUC 0.376 vs 0.371), so I'd keep logistic regression if explainability mattered more than a small lift."

6. How did you choose the threshold? "I computed campaign profit at every threshold using offer cost, save rate and customer value. The best was 0.23, which made about three times the profit of 0.5."

7. SHAP vs feature importance? "Built-in importance gives one global ranking without direction. SHAP gives direction and per-customer explanations, which tell the retention team what to do for each customer."

8. How would you know the campaign worked? "A randomised holdout of high-risk customers who don't get the offer, then compare churn between the groups."

More practice: data analyst interview questions and Python interview questions.

How to put this project on your resume

Weak: "Built a churn prediction model using XGBoost with 82% accuracy." (Accuracy is the wrong metric, and nothing ties the work to a decision.)

Strong:

  • "Built a churn model for 20,000 prepaid subscribers (Python, scikit-learn, XGBoost). Caught a leaky feature that inflated ROC-AUC to 0.997, and lifted PR-AUC from 0.18 (random) to 0.40."
  • "Chose the offer threshold by campaign profit, earning 3× the default-threshold profit (₹50.9K vs ₹16.3K per 4,000 customers). Used SHAP to route network-driven risk to callbacks instead of discounts."

Say the data is synthetic if it is, link the notebook on GitHub, and be ready to walk through Steps 4, 7 and 8. Those are where interviewers probe. More ideas: data analysis projects and writing a data analyst resume.

Frequently asked questions

What is customer churn prediction in machine learning?

It's a binary classification task: for each active customer, a model estimates the probability that they stop using the product within a defined future window, using only data available at the prediction date. The scores are used to decide who receives a retention action.

Which machine learning algorithm is best for churn prediction?

There's no single best one. Start with logistic regression as an explainable baseline, then try gradient boosting such as XGBoost or LightGBM, which usually handle interactions and non-linear patterns better. In this project XGBoost scored a PR-AUC of 0.404 against 0.380 for logistic regression, a small gain, which is common when the main signals are simple.

Which dataset can I use for a churn prediction project?

The IBM Telco Customer Churn dataset on Kaggle is the most common public choice, but it describes US monthly contracts. This post generates a synthetic Indian prepaid dataset with code, so you can control the size, rerun it and explain every column. If you use real company data, remove personal details first.

What is a good accuracy for a churn model?

Accuracy is the wrong yardstick for churn because most customers don't churn. A model that predicts "nobody churns" scored 81.9% accuracy here while catching zero churners. Use PR-AUC, and precision and recall at your chosen threshold. Realistic churn ROC-AUC values often fall between 0.70 and 0.85; scores above 0.95 usually mean leakage.

How do you handle imbalanced data in churn prediction?

Use stratified train/test splits and cross-validation, evaluate with PR-AUC, and pick the decision threshold from business costs. Class weights such as scale_pos_weight or resampling such as SMOTE can raise recall, but they distort predicted probabilities, so recalibrate before using the probabilities in rupee calculations.

What is data leakage in churn prediction?

Leakage is when a feature contains information from after the prediction date, such as a "days since last recharge" value pulled at extraction time or a port-out request flag. The model looks excellent in testing (ROC-AUC 0.997 here) but fails in production because that information doesn't exist when you need the prediction.

What are SHAP values in simple terms?

SHAP values split one prediction into contributions from each feature, showing how much each pushed the churn risk up or down from the average. They help explain individual customers ("high call drops and three complaints drove this score") and the model overall, but they describe the model's behaviour, not real-world causes.

Is churn prediction a good project for a data analyst or a data scientist?

Both. An analyst version covers cleaning, EDA, churn rates by segment and recommendations, as in Steps 2 and 3. A data scientist version adds modelling, evaluation, threshold selection and SHAP. Showing the business decision and its rupee impact is what makes either version stand out.

Recommended reading and practice on Skillancy

Sources

Reproducibility note

All code was run in order on 29 November 2026 with Python 3.13, pandas 2.3.3, NumPy 2.3.5, scikit-learn 1.7.2, XGBoost 3.4.1, SHAP 0.54.1 and Matplotlib 3.11.2, and every output above is copied from that run. The dataset is synthetic: it's generated by the Step 1 code with a fixed seed (42), so the same numbers appear on every run with these versions. Other library versions can shift the later decimals. The offer cost, save rate, margin and 12-month value in Step 8 are illustrative assumptions, not industry figures. The chart-styling lines are trimmed in the post; the deployment ideas (joblib, FastAPI, Streamlit) were not run.

Learn it live: Churn prediction is a capstone project in both of our programs. In Data Science with AI you build the full model, from XGBoost and imbalanced data to SHAP, and in Data Analytics with Agentic AI you do the churn and behaviour analysis in pandas, with mentors reviewing your work. Not sure which fits you? Talk to a mentor. Learn. Build. Get hired.
Newsletter

Get the Skillancy field notes

One email a week: AI and analytics guides, cohort dates and hiring signals. No spam, unsubscribe anytime.