Lesson 8 of 9
Mini Project: Customer Churn Prediction Engine with XGBoost & SHAP Explanations
Build an end-to-end production customer churn prediction engine for a subscription telecom business. The pipeline handles imbalanced churn rates, pre-processes mixed categorical features via ColumnTransformer, trains a modern Gradient Boosted Decision Tree, tunes the decision threshold for financial recall, and generates individualized customer risk explainability reports.
Complete Telecom Churn Engine with Explainability
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.metrics import classification_report, roc_auc_score, average_precision_score
# 1. SYNTHETIC TELECOM CHURN DATASET
np.random.seed(42)
n_users = 4000
df_churn = pd.DataFrame({
'account_length_months': np.random.randint(1, 72, size=n_users),
'monthly_bill': np.random.normal(70, 25, size=n_users).clip(20, 150),
'customer_service_calls': np.random.poisson(lam=1.5, size=n_users),
'international_plan': np.random.choice(['no', 'yes'], size=n_users, p=[0.9, 0.1]),
'contract_type': np.random.choice(['Month-to-month', 'One year', 'Two year'], size=n_users, p=[0.55, 0.25, 0.20])
})
# Ground truth risk (churn ~15%)
risk = (
0.02 * df_churn['monthly_bill']
+ 0.6 * df_churn['customer_service_calls']
- 0.05 * df_churn['account_length_months']
+ 1.2 * (df_churn['contract_type'] == 'Month-to-month')
- 3.5
)
df_churn['churned'] = (1 / (1 + np.exp(-risk)) > np.random.uniform(0, 1, size=n_users)).astype(int)
# 2. SPLIT BEFORE PREPROCESSING
X = df_churn.drop(columns=['churned'])
y = df_churn['churned']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)
# 3. COLUMN TRANSFORMER & PIPELINE
preprocessor = ColumnTransformer(
transformers=[
('num', StandardScaler(), ['account_length_months', 'monthly_bill', 'customer_service_calls']),
('cat', OneHotEncoder(drop='first', sparse_output=False), ['international_plan', 'contract_type'])
]
)
pipeline = Pipeline([
('prep', preprocessor),
('hgb', HistGradientBoostingClassifier(
class_weight='balanced',
max_iter=100,
random_state=42
))
])
# 4. CROSS-VALIDATION EVALUATION
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
cv_scores = cross_val_score(pipeline, X_train, y_train, cv=cv, scoring='roc_auc')
print(f"5-Fold CV ROC-AUC: {cv_scores.mean():.4f} (ยฑ {cv_scores.std():.4f})")
# 5. TEST SET EVALUATION
pipeline.fit(X_train, y_train)
y_probs = pipeline.predict_proba(X_test)[:, 1]
print(f"\nHeld-Out Test ROC-AUC : {roc_auc_score(y_test, y_probs):.4f}")
print(f"Held-Out Test PR-AUC : {average_precision_score(y_test, y_probs):.4f}")
# 6. OPERATIONAL THRESHOLD OPTIMIZATION (Targeting 80% Recall)
thresholds = np.linspace(0.1, 0.9, 81)
recalls = [np.sum((y_probs >= t) & (y_test == 1)) / np.sum(y_test == 1) for t in thresholds]
opt_thresh = thresholds[np.argmax(np.array(recalls) <= 0.82)]
y_pred_opt = (y_probs >= opt_thresh).astype(int)
print(f"\nOptimized Operational Threshold: {opt_thresh:.2f}")
print(classification_report(y_test, y_pred_opt, target_names=['Retain', 'Churn'], digits=3))Pro Tip: Deploying Retention Interventions Cost-Effectively
Do not offer discounts to all users predicted to churn. Segment churn risk against customer lifetime value (LTV): Offer personalized VIP retention packages to high-LTV / high-churn users, while ignoring low-LTV / high-churn users whose retention cost exceeds their expected margin.
MlCustomerChurnProject Visual Representation
Hands-On Challenge: Build a Customer Risk Explainer Card
Write a function `generate_retention_card(user_data)` that outputs the customer's predicted churn probability alongside the top 2 features driving their individual risk score (e.g., 'Customer Service Calls: +32% risk').
Quick Quiz & Key Concept Checks
Common Pitfall: Evaluating Churn Models on Static Time Slices
Churn behavior changes dynamically over time. Evaluating a model on randomly shuffled splits conceals temporal drift. In production, train on users from Months 1-6 and evaluate on Month 7.