Pulse Data Hub

Customer Churn Prediction in Python: A Telco Example

Customer churn prediction in Python means estimating, from account data, which customers are likely to cancel, so you can act before they do. This guide builds one on 7,043 real telecom customers, shows what the data says about who leaves, and reports exactly how well the model works, including where it falls short.

The data is the IBM Telco Customer Churn sample, a public file with one row per customer: contract, tenure, services, billing and whether they left. It is a sample dataset published by IBM, not data from a live company. Code was run with pandas 3.0.5 and scikit-learn 1.9.1.

Two charts of the IBM telco churn data: churn rate by contract type, 42.7 percent month to month against 2.8 percent for two-year contracts, and a gain curve showing that contacting the top 20 percent of scored customers reaches 48.8 percent of churners.
Left: churn rate by contract type. Right: share of churners caught when you contact the top-scored customers (test set).

Step 1: Load the data and check it

import pandas as pd

url = "https://raw.githubusercontent.com/IBM/telco-customer-churn-on-icp4d/master/data/Telco-Customer-Churn.csv"
df = pd.read_csv(url)
print(df.shape, "churn %.1f%%" % ((df.Churn == "Yes").mean() * 100))

bad = pd.to_numeric(df.TotalCharges, errors="coerce").isna()
print("TotalCharges blank:", bad.sum(), "tenure of those:", df.tenure[bad].unique())
(7043, 21) churn 26.5%
TotalCharges blank: 11 tenure of those: [0]

26.5% of customers left, so a model that always says “stays” is right 73.5% of the time and finds nobody. That is the number to beat, and it is why accuracy alone is a poor score for churn. The 11 blank TotalCharges values all belong to customers with tenure 0, brand-new accounts that have not been billed yet, so setting them to 0 is reasonable. For more on this kind of check, see our guide to cleaning and preprocessing data in Python.

df["TotalCharges"] = pd.to_numeric(df.TotalCharges, errors="coerce").fillna(0)
df["y"] = (df.Churn == "Yes").astype(int)

for c in ["Contract", "InternetService", "PaymentMethod"]:
    print(df.groupby(c).y.agg(["mean", "size"]))

Step 2: See who leaves before modelling

GroupCustomersChurn rate
Month-to-month contract3,87542.7%
One-year contract1,47311.3%
Two-year contract1,6952.8%
Fiber optic internet3,09641.9%
DSL internet2,42119.0%
No internet service1,5267.4%
Pays by electronic check2,36545.3%
Pays by automatic card or bank transfer3,06615.2% to 16.7%
Tenure 0 to 12 months2,18647.4%
Tenure 49 to 72 months2,2399.5%

The pattern is strong. Month-to-month customers churn at 15 times the rate of two-year customers. Combining three risk factors, month-to-month plus fiber optic plus tenure of 12 months or less, gives 916 customers with a 70.2% churn rate. These are differences between groups, not proof of cause: customers who plan to leave anyway may simply choose flexible contracts.

Step 3: Split the data and build two models

We hold out 25% of customers as a test set, stratified so both parts keep the 26.5% churn rate (5,282 train, 1,761 test). Preprocessing lives inside a pipeline so the scaler and encoder learn only from training rows. The approach is the same one we use in building a machine learning model with scikit-learn.

from sklearn.model_selection import train_test_split, cross_val_score, StratifiedKFold
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.dummy import DummyClassifier
from sklearn.metrics import roc_auc_score, precision_score, recall_score

X = df.drop(columns=["customerID", "Churn", "y"])
y = df.y
Xtr, Xte, ytr, yte = train_test_split(X, y, test_size=0.25, stratify=y, random_state=0)

num = ["tenure", "MonthlyCharges", "TotalCharges", "SeniorCitizen"]
cat = [c for c in X.columns if c not in num]

models = {
    "majority": DummyClassifier(strategy="most_frequent"),
    "logistic": make_pipeline(
        ColumnTransformer([("n", StandardScaler(), num),
                           ("c", OneHotEncoder(handle_unknown="ignore"), cat)]),
        LogisticRegression(max_iter=2000)),
    "boosting": make_pipeline(
        ColumnTransformer([("n", "passthrough", num),
                           ("c", OneHotEncoder(handle_unknown="ignore", sparse_output=False), cat)]),
        HistGradientBoostingClassifier(random_state=0)),
}
cv = StratifiedKFold(5, shuffle=True, random_state=0)
for name, m in models.items():
    cvauc = cross_val_score(m, Xtr, ytr, cv=cv, scoring="roc_auc").mean()
    m.fit(Xtr, ytr)
    p = m.predict_proba(Xte)[:, 1]
    pred = (p >= 0.5).astype(int)
    print(name, "cv auc %.3f" % cvauc, "test auc %.3f" % roc_auc_score(yte, p),
          "acc %.3f" % (pred == yte).mean(),
          "prec %.3f rec %.3f" % (precision_score(yte, pred, zero_division=0), recall_score(yte, pred)))
majority cv auc 0.500 test auc 0.500 acc 0.735 prec 0.000 rec 0.000
logistic cv auc 0.845 test auc 0.844 acc 0.792 prec 0.630 rec 0.525
boosting cv auc 0.832 test auc 0.830 acc 0.789 prec 0.630 rec 0.499

The plain logistic regression (test ROC AUC 0.844) beat gradient boosting (0.830). The gap is small and we ran one split, so call them about equal. The useful lesson is that on tabular data with a few strong drivers, a simple model is a serious baseline. Two single-feature models show how much comes from one column: tenure alone scores an AUC of 0.754, and contract type alone 0.742. If you want to see tree ensembles in more depth, read random forests explained.

Step 4: Turn scores into a contact list

At the default 0.5 cut-off the logistic model flags 389 of 1,761 test customers. 63.0% of them really churn (precision) but it only finds 52.5% of all churners (recall). Lowering the cut-off to 0.3 flags 663 customers, finds 76.9% of churners, and precision falls to 54.1%. Which is right depends on what a retention offer costs compared with a lost customer. That cost is a business input the data cannot supply.

Ranking is simpler to act on. Sort customers by predicted risk and contact the top slice:

Contact the topShare of churners caughtChurn rate inside the group
10% of customers27.2%72.2%
20% of customers48.8%64.8%
30% of customers65.5%58.0%

Contacting the riskiest 20% reaches nearly half of the people who will leave, with 2.4 times the base churn rate. That is the way to judge a churn model: not accuracy, but how many leavers you reach for a given effort.

What the model learned

The largest logistic regression coefficients on standardized and one-hot inputs point the way you would expect. Longer tenure lowers churn risk the most (coefficient -1.31), followed by a two-year contract (-0.70), DSL internet (-0.38) and having phone service (-0.34). Month-to-month contracts (+0.56), fiber optic (+0.24) and electronic-check payment (+0.20) raise it. Treat these as signals, not causes. TotalCharges is almost tenure times monthly price, so these inputs overlap and individual coefficients are not clean effects.

Limits of this example

This is one snapshot of customers with a yes or no outcome. It does not say when a customer left, and a real project needs a clear time window: predict churn in the next 30 days using only what was known today. We used a single random split, so the AUC could move a few hundredths with another split. The file is a published sample, so these rates will not match your business. Nothing here estimates the money saved by a retention campaign. To work through the data cleaning and exploration that comes before modelling, start with exploratory data analysis in Python. The scikit-learn documentation describes ColumnTransformer, and the data is on IBM’s GitHub.

FAQ

What is the best model for customer churn prediction in Python?

There is no single best one. On this dataset logistic regression (AUC 0.844) matched gradient boosting (0.830). Start with logistic regression as a baseline and use a boosted model only if it clearly beats it on held-out data.

Why is accuracy a bad metric for churn?

Because most customers stay. Here, always predicting “stays” gives 73.5% accuracy and finds no churners. Use ROC AUC, precision and recall, or the share of churners reached in the top slice.

Which customers churn most?

In this data: month-to-month contracts (42.7%), new customers in their first year (47.4%), fiber optic users (41.9%) and electronic-check payers (45.3%). Customers with a two-year contract churned at 2.8%.

Newsletter Signup Form

Latest tutorials

Latest articles

On this page
Verified by MonsterInsights