Building a Churn Prediction Model in Python
Customer churn occurs when a customer stops using a product or service, cancels a subscription, switches providers, or becomes inactive for a defined period. Predicting this behavior helps companies focus retention efforts on customers who are likely to leave. In sectors such as telecom, banking, insurance, ecommerce, SaaS, and digital payments, even a modest improvement in retention can have a measurable effect on revenue.
A churn prediction model combines customer history, engagement signals, transaction data, and service interactions to estimate the probability of attrition. Python provides a practical environment for this work because libraries such as pandas, scikit-learn, matplotlib, seaborn, and imbalanced-learn support the complete machine learning workflow, from data preparation to model monitoring.
Define Churn And Assemble The Dataset
Start by defining churn in business terms rather than treating it as a purely technical label. A prepaid telecom customer might be classified as churned after 60 days without a recharge, while a SaaS customer may churn when a subscription is cancelled. The observation window, prediction window, and churn event must be explicit. For example, use the first six months of activity to predict whether a customer will leave during the following 30 days.
A typical customer-level dataset may include fields such as customer_id, tenure_months, monthly_charges, contract_type, payment_method, support_tickets, login_frequency, last_purchase_days, and churn. The target variable should contain a consistent binary value, such as 1 for churn and 0 for retained customers.
import pandas as pd
df = pd.read_csv("customer_churn.csv")
print(df.shape)
print(df.head())
print(df["churn"].value_counts(normalize=True))
Avoid using information that became available only after the prediction date. A cancellation request, final invoice, or account closure code may make the model appear highly accurate while offering no practical warning. This problem, known as target leakage, is one of the most common errors in churn analytics.
Clean And Prepare Customer Data
Inspect data types, missing values, duplicate records, and unusual values before training a classifier. Numeric columns may contain text symbols, while categorical fields can include inconsistent labels such as Monthly, monthly, and Month-to-month. Standardizing these values improves the reliability of downstream transformations.
df.info()
print(df.isna().sum().sort_values(ascending=False).head(10))
df = df.drop_duplicates(subset="customer_id")
df["total_charges"] = pd.to_numeric(df["total_charges"], errors="coerce")
df["churn"] = df["churn"].map({"Yes": 1, "No": 0})
Missing values should be handled according to their meaning. Median imputation is often suitable for skewed numeric variables, while the most frequent category or an explicit "Unknown" value can work for categorical data. Dropping rows may be acceptable for a small number of incomplete records, but removing many customers can introduce selection bias.
Separate predictors from the target and exclude identifiers unless they carry a genuine behavioral signal. Split the data before fitting preprocessing steps so that information from the test set does not influence imputation, scaling, or category encoding.
Explore Patterns And Engineer Features
Exploratory data analysis helps identify relationships between customer behavior and attrition. Compare churn rates across contract type, tenure bands, payment methods, service plans, region, and acquisition channel. A simple group analysis can reveal useful patterns:
print(
df.groupby("contract_type")["churn"]
.mean()
.sort_values(ascending=False)
)
Visualizations can expose nonlinear trends that summary statistics miss. Histograms of tenure, box plots of monthly charges, and churn-rate bar charts are useful starting points. A high churn rate among new customers may indicate onboarding problems, while elevated churn among long-term customers may point to price increases or weak loyalty programs.
Feature engineering converts raw records into signals a model can use. Useful variables include average monthly spend, change in usage over the last three months, number of support contacts, days since last activity, payment failures, discount expiration, and the ratio of complaints to completed transactions. For event-level data, aggregate activity within a fixed time window rather than allowing future events into the feature set.
df["avg_monthly_spend"] = (
df["total_charges"] / df["tenure_months"].clip(lower=1)
)
df["support_rate"] = (
df["support_tickets"] / df["tenure_months"].clip(lower=1)
)
df["is_new_customer"] = (df["tenure_months"] <= 3).astype(int)
Keep features interpretable when the model will guide retention campaigns. A variable such as days_since_last_login is easier for a customer success team to act on than an opaque aggregate with no business meaning. Document how each feature is calculated, its time reference, and the expected direction of its relationship with churn.
Build A Reproducible Baseline Model
A logistic regression model is an effective baseline for binary churn classification. It is fast, explainable, and produces probabilities that can be ranked for campaign targeting. For mixed data types, use a scikit-learn pipeline with median imputation and standardization for numeric features, plus imputation and one-hot encoding for categorical features.
from sklearn.model_selection import train_test_split
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from sklearn.linear_model import LogisticRegression
target = "churn"
X = df.drop(columns=[target, "customer_id"])
y = df[target]
numeric_features = X.select_dtypes(include="number").columns
categorical_features = X.select_dtypes(exclude="number").columns
numeric_pipe = Pipeline([
("imputer", SimpleImputer(strategy="median")),
("scaler", StandardScaler())
])
categorical_pipe = Pipeline([
("imputer", SimpleImputer(strategy="most_frequent")),
("encoder", OneHotEncoder(handle_unknown="ignore"))
])
preprocessor = ColumnTransformer([
("num", numeric_pipe, numeric_features),
("cat", categorical_pipe, categorical_features)
])
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=42
)
model = Pipeline([
("preprocessor", preprocessor),
("classifier", LogisticRegression(
max_iter=1000, class_weight="balanced"
))
])
model.fit(X_train, y_train)
Stratification preserves the churn proportion in both partitions. If records are time-dependent, use a chronological split instead: train on earlier customers or observation periods and test on later ones. This more closely represents how the model will perform after deployment.
Class imbalance requires special attention. If only 8% of customers churn, predicting “retained” for everyone produces 92% accuracy but no useful intervention list. Class weights, threshold adjustment, oversampling, or synthetic techniques such as SMOTE can help, but they should be applied only within the training process.
Compare Algorithms And Tune The Pipeline
After establishing a baseline, compare logistic regression with tree-based approaches. Decision trees provide simple rules but can overfit. Random forests capture nonlinear relationships and interactions, while gradient boosting models often deliver strong predictive performance on tabular customer data. XGBoost, LightGBM, and CatBoost are popular alternatives when the project permits additional dependencies.
Use cross-validation on the training data for model selection. Randomized search is often more efficient than testing every possible parameter combination.
from sklearn.model_selection import RandomizedSearchCV
parameters = {
"classifier__C": [0.01, 0.1, 1, 10],
"classifier__solver": ["liblinear", "lbfgs"]
}
search = RandomizedSearchCV(
model,
param_distributions=parameters,
n_iter=6,
scoring="roc_auc",
cv=5,
random_state=42,
n_jobs=-1
)
search.fit(X_train, y_train)
best_model = search.best_estimator_
Tune against a metric that reflects the business objective. ROC AUC measures ranking ability across thresholds, but it can look optimistic when churn is rare. Precision-recall AUC, recall at a fixed campaign capacity, precision among the top 10% of scored customers, and expected retention value may be more useful for operational decisions.
Measure Performance And Explain Predictions
Evaluate the final model on untouched test data. A confusion matrix shows how many customers were correctly and incorrectly classified at a chosen threshold. Precision answers how many flagged customers actually churned, while recall measures how many churners the model identified. The appropriate balance depends on intervention cost and the value of saving a customer.
from sklearn.metrics import (
roc_auc_score, average_precision_score,
classification_report, confusion_matrix
)
probabilities = best_model.predict_proba(X_test)[:, 1]
predictions = (probabilities >= 0.40).astype(int)
print("ROC AUC:", roc_auc_score(y_test, probabilities))
print("PR AUC:", average_precision_score(y_test, probabilities))
print(confusion_matrix(y_test, predictions))
print(classification_report(y_test, predictions))
The default threshold of 0.50 is not automatically correct. If a retention team can contact only 2,000 customers per month, rank all customers by predicted probability and select the highest-risk group. If incentives are expensive, a higher threshold may produce a smaller, more precise list. Threshold selection should be based on expected profit, campaign capacity, and the cost of false positives.
Model explanations help analysts and business teams trust the result. Logistic regression coefficients show the direction and relative effect of encoded variables, although coefficients should be interpreted carefully after scaling. SHAP values can explain individual predictions for tree-based models. Review explanations for potential bias: a location, language, or payment variable may act as a proxy for protected characteristics.
Compare Model Choices In Practice
Different algorithms offer different trade-offs among transparency, performance, training speed, and maintenance effort. The best choice is not always the model with the highest validation score. A slightly less accurate model may be preferable when retention managers need clear explanations or when the data changes frequently.
| Model |
Strengths |
Limitations |
Suitable Use |
| Logistic regression |
Fast, interpretable, probability-based |
Limited nonlinear pattern detection |
Baseline and regulated settings |
| Decision tree |
Easy to visualize and explain |
Prone to overfitting |
Simple rule discovery |
| Random forest |
Robust, handles interactions, good tabular performance |
Larger and less transparent |
General-purpose churn scoring |
| Gradient boosting |
Strong predictive accuracy and flexible patterns |
Requires tuning and monitoring |
Production prioritization |
| Neural network |
Can model complex high-volume data |
Less interpretable and data-hungry |
Large behavioral or event datasets |
Validation should also consider calibration. A customer predicted at 0.70 risk should churn roughly 70% of the time within a comparable group if the probabilities are well calibrated. Calibration curves, Brier score, and methods such as Platt scaling or isotonic regression can improve the usefulness of probability estimates.
Track performance after deployment using a fixed evaluation window. Monitor changes in churn prevalence, feature distributions, recall, precision, calibration, and campaign outcomes. Population drift may occur when pricing changes, competitors launch new products, or customer behavior shifts. Retraining should follow a documented schedule or be triggered by meaningful performance deterioration.
Turn Predictions Into Retention Actions
A churn score becomes valuable when it supports a specific decision. Segment customers by risk and likely need rather than sending the same offer to everyone. A high-risk customer with repeated payment failures may need billing support, while a high-risk customer with declining usage may benefit from onboarding, product education, or a relevant plan recommendation.
- Define the churn event, observation window, and prediction horizon before modeling.
- Prevent target leakage by using only information available at scoring time.
- Compare recall, precision, PR AUC, lift, and campaign capacity instead of relying on accuracy.
- Use explainable segments and tailored interventions for high-risk customers.
- Monitor calibration, drift, fairness, and realized retention after deployment.
Test interventions with randomized holdout groups wherever possible. A model can identify customers who are likely to leave, but it does not prove that a discount or phone call will change their decision. Incremental impact requires comparing treated customers with similar customers who receive no intervention.
Document the full workflow in a reproducible notebook or production pipeline, including data definitions, feature logic, model version, threshold, validation results, and monitoring rules. This creates a dependable churn analytics system that can evolve with customer behavior while remaining useful to analysts, decision-makers, and retention teams.