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
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
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?
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?
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.
- 1Precision = TP / (TP + FP) = 3 / (3 + 1) = 0.75.
- 2Recall = TP / (TP + FN) = 3 / (3 + 1) = 0.75.
- 3F1 = 2 × precision × recall / (precision + recall) = 2 × 0.75 × 0.75 / 1.50 = 0.75.
- 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.
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 = stayedStep 2: Split before preprocessing
For a real dataset, stratification preserves the churn proportion. The fixed random state makes the teaching split reproducible.
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.
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.
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
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?
12. Failure Analysis
Failure mode → diagnosis → response
13. Improve the Project
14. Production Considerations
What changes beyond the notebook
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.