Freedom Sale
Independence Day Special — Unlock the AI Path 70% off our most popular AI course · Limited time offer
--Days
--Hrs
--Min
--Sec
Claim Your Discount
✦ Intermediate ⏱ 60 min

📉 Build a Customer Churn Predictor with Logistic Regression

🎯 What You'll Build

A binary classifier that predicts which customers are likely to cancel — with a confusion matrix, ROC curve, and feature importance.

📋 What You'll Need

1

Load and preprocess

Encode categoricals and scale numeric features.

import pandas as pd
from sklearn.preprocessing import LabelEncoder, StandardScaler

df = pd.read_csv('WA_Fn-UseC_-Telco-Customer-Churn.csv')
df['TotalCharges'] = pd.to_numeric(df['TotalCharges'], errors='coerce').fillna(0)
df.drop('customerID', axis=1, inplace=True)

# Encode binary/categorical columns
le = LabelEncoder()
for col in df.select_dtypes(include='object').columns:
    df[col] = le.fit_transform(df[col])

X = df.drop('Churn', axis=1)
y = df['Churn']

scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
print("Preprocessed shape:", X_scaled.shape)
Preprocessed shape: (7043, 19)
2

Train and evaluate

Fit logistic regression and print a classification report.

from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report

X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.2, random_state=42)

model = LogisticRegression(max_iter=500, random_state=42)
model.fit(X_train, y_train)

y_pred = model.predict(X_test)
print(classification_report(y_test, y_pred, target_names=['Stayed', 'Churned']))
precision    recall  f1-score   support
      Stayed       0.84      0.90      0.87      1036
     Churned       0.66      0.52      0.58       373
    accuracy                           0.81      1409
3

ROC curve and feature importance

Visualise model performance and which features matter most.

from sklearn.metrics import roc_curve, auc
import matplotlib.pyplot as plt, numpy as np

y_prob = model.predict_proba(X_test)[:, 1]
fpr, tpr, _ = roc_curve(y_test, y_prob)
roc_auc = auc(fpr, tpr)

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 5))
ax1.plot(fpr, tpr, color='#4f46e5', lw=2, label=f'AUC = {roc_auc:.2f}')
ax1.plot([0,1],[0,1], 'k--')
ax1.set_title('ROC Curve'); ax1.legend(); ax1.set_xlabel('FPR'); ax1.set_ylabel('TPR')

coef = pd.Series(np.abs(model.coef_[0]), index=X.columns).sort_values().tail(10)
coef.plot(kind='barh', ax=ax2, title='Top 10 Feature Importances')
plt.tight_layout()
plt.savefig('churn_model.png', dpi=150)
print(f"ROC-AUC: {roc_auc:.2f}")
ROC-AUC: 0.85
💡 Tip: Try XGBoost or a Random Forest — they typically reach 0.89+ AUC on this dataset with minimal tuning.

🎉 You Did It!

You built a complete churn prediction pipeline from raw CSV to ROC curve. This is a portfolio project that directly maps to real business value.

Found something wrong?

Spotted a bug, broken code, or something that doesn't look right? Tell us what's off and we'll fix it.