In this project you build a complete customer churn model: it predicts which mobile customers are likely to leave, so the company can contact them first. The project brings together many lessons from this series: missing values, categorical encoding, pipelines, model comparison with ROC AUC, choosing a threshold, permutation importance and saving the model for later use.
In this project you will
- Prepare mixed numeric and text data with one
ColumnTransformer - Compare two models fairly with cross-validated ROC AUC
- Pick a decision threshold that suits the business
- Explain the model with permutation importance
- Save the whole pipeline with
jobliband score a new customer
Helpful background: pipelines, ROC and AUC and permutation importance.
The Complete Script
The data is generated inside the script, so you can run it anywhere without downloading anything. Customers who are new, call support often or use prepaid plans are more likely to leave.
import joblib
import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.impute import SimpleImputer
from sklearn.inspection import permutation_importance
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report, roc_auc_score
from sklearn.model_selection import cross_val_score, train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
# 1. Data: a made-up mobile operator with 3,000 customers
rng = np.random.default_rng(11)
n = 3000
df = pd.DataFrame({
"tenure_months": rng.integers(1, 72, n),
"monthly_bill": rng.normal(550, 150, n).round(),
"support_calls": rng.poisson(1.2, n),
"data_gb": rng.gamma(2, 4, n).round(1),
"plan": rng.choice(["prepaid", "postpaid", "family"], n, p=[0.5, 0.35, 0.15]),
})
risk = (-1.2 - 0.04 * df.tenure_months + 0.6 * df.support_calls
+ 0.002 * (df.monthly_bill - 550) + np.where(df.plan == "prepaid", 0.8, 0))
df["churned"] = (rng.random(n) < 1 / (1 + np.exp(-risk))).astype(int)
df.loc[rng.random(n) < 0.08, "data_gb"] = np.nan # some usage records are missing
print("Customers:", len(df), "| churn rate:", round(df.churned.mean(), 3))
# 2. Split, keeping the churn rate the same in both parts
X, y = df.drop(columns="churned"), df["churned"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, stratify=y, random_state=0)
# 3. Preprocessing for numeric and text columns
numeric = ["tenure_months", "monthly_bill", "support_calls", "data_gb"]
prep = ColumnTransformer([
("num", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()), numeric),
("cat", OneHotEncoder(handle_unknown="ignore"), ["plan"]),
])
# 4. Compare two models with cross-validated ROC AUC
models = {
"logistic": make_pipeline(prep, LogisticRegression(max_iter=1000)),
"boosting": make_pipeline(prep, HistGradientBoostingClassifier(max_depth=3, random_state=0)),
}
for name, m in models.items():
auc = cross_val_score(m, X_train, y_train, cv=5, scoring="roc_auc").mean()
print(f"{name:<9} CV ROC AUC {auc:.3f}")
# 5. Final check on the untouched test set
best = models["logistic"].fit(X_train, y_train)
proba = best.predict_proba(X_test)[:, 1]
print("\nTest ROC AUC:", round(roc_auc_score(y_test, proba), 3))
pred = (proba >= 0.35).astype(int) # lower threshold: catch more leavers
print(classification_report(y_test, pred, target_names=["stays", "leaves"], digits=2))
# 6. Which columns drive the predictions?
imp = permutation_importance(best, X_test, y_test, scoring="roc_auc", n_repeats=10, random_state=0)
for col, v in sorted(zip(X.columns, imp.importances_mean), key=lambda t: -t[1]):
print(f" {col:<14} {round(v, 3) + 0.0:.3f}")
# 7. Save and reload the whole pipeline
joblib.dump(best, "/tmp/churn_model.joblib")
loaded = joblib.load("/tmp/churn_model.joblib")
new = pd.DataFrame([{"tenure_months": 3, "monthly_bill": 700, "support_calls": 4,
"data_gb": np.nan, "plan": "prepaid"}])
print("\nRisk for a new customer:", round(loaded.predict_proba(new)[0, 1], 2))
Output
Customers: 3000 | churn rate: 0.234
logistic CV ROC AUC 0.777
boosting CV ROC AUC 0.752
Test ROC AUC: 0.771
precision recall f1-score support
stays 0.83 0.87 0.85 575
leaves 0.50 0.43 0.46 175
accuracy 0.77 750
macro avg 0.66 0.65 0.66 750
weighted avg 0.75 0.77 0.76 750
tenure_months 0.120
support_calls 0.107
plan 0.041
monthly_bill 0.016
data_gb 0.000
Risk for a new customer: 0.9
Step by Step
1. The data
There are 3,000 customers and 23.4% of them left. About 8% of the data_gb values are missing, as often happens with usage logs. The plan column is text.
2. The split
stratify=y keeps the churn rate the same in the training and test sets. The test set (750 customers) is not touched until the very end.
3. Preprocessing
Numeric columns get a median fill and scaling. The plan column is one-hot encoded; handle_unknown="ignore" means a plan name that did not exist in training will not crash the model later.
4. Comparing models
Both candidates share the same preprocessing and are scored with 5-fold cross-validation on the training set only. Logistic regression (0.777) beats gradient boosting (0.752). The true pattern in this data is close to a straight-line combination of the inputs, which is exactly what logistic regression fits. Never assume the fancier model wins; measure it.
5. Test score and threshold
The test ROC AUC of 0.771 matches the cross-validation result, so the model was not overfitted to the training data. A threshold of 0.35 instead of 0.5 flags more customers. Of the customers it flags, 50% really leave, and it catches 43% of all leavers. If contacting a customer is cheap, a lower threshold catches more leavers at the cost of more wasted calls.
6. Explaining the model
Tenure and support calls drive the predictions most, followed by plan type. data_gb scores 0.000: the model gets no help from it, which is correct, because churn was generated without it. Because the importance is measured on the whole pipeline, it reports the original columns, such as plan, not the one-hot columns.
7. Saving and reusing
joblib.dump saves the entire pipeline, including the imputer’s medians, the scaler’s means and the encoder’s categories. After joblib.load, a raw new row can be passed straight in. The new prepaid customer, three months in with four support calls, gets a churn risk of 0.9, even though their data usage is missing.
Taking It Further
- Tune
Cfor logistic regression with grid search, usingscoring="roc_auc". - Choose the threshold from costs: for example, a call costs 50 and keeping a customer is worth 2,000.
- Add a feature such as
bill_per_gb, and check whether cross-validated AUC improves. - Look at learning curves to see whether more customer data would help.
Common Mistakes in Churn Projects
- Using information from after the customer left, such as “account closed date”, as a feature. It makes the model look perfect but useless in practice.
- Reporting accuracy. Predicting “stays” for everyone already gives 76.7% accuracy on this test set.
- Saving only the model, not the pipeline, so new data is not prepared the same way.
- Never retraining. Customer behaviour changes; check the model’s performance on recent data regularly.
Practice Exercises
Exercise 1. Print how many test customers the model flags at thresholds 0.2, 0.35 and 0.5.
Show answer
for t in [0.2, 0.35, 0.5]:
print(t, (proba >= t).sum())
The count falls as the threshold rises. The business can pick the threshold that matches how many customers its team can call.
Exercise 2. List the ten test customers with the highest churn risk.
Show answer
top = X_test.assign(risk=proba).sort_values("risk", ascending=False).head(10)
print(top)
Frequently Asked Questions
What is customer churn?
Churn is when a customer stops using a service, such as cancelling a subscription or moving to another mobile operator. The churn rate is the share of customers who leave in a period.
Is joblib safe for sharing models?
Only load joblib or pickle files from sources you trust, because loading one can run code. Also load the model with the same scikit-learn version that saved it.
Summary
- One pipeline handles missing values, scaling, encoding and the model together.
- Compare models with cross-validation on training data, then check once on the test set.
- Choose the threshold from business costs, not the default 0.5.
- Explain the model with permutation importance and save the full pipeline.
