Editor

Generate a Churn Risk Report

Advanced · Write the code · from Predict Customer Churn: End-to-End Data Analysis (with sklearn)

From the lesson: Step 7: Identify At-Risk Customers

The real business value isn't just knowing that churn happens - it's knowing who is most likely to churn and why. We can use the model's predicted probabilities to rank customers by risk and generate actionable insights for the retention team.

Read this part of the lesson

Using model.predict_proba(), get the churn probability for each customer. Add it as a churn_risk column to the original DataFrame. Then:

1. Sort by churn_risk descending.

2. Print "=== CHURN RISK REPORT ===" as a header.

3. Print the top 5 at-risk customers showing customer_id, tenure_months, monthly_charges, contract, and churn_risk (formatted to 2 decimal places).

4. Print a summary: "High risk customers (>70%): N" with the count.

import pandas as pd
import numpy as np
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
data = {
'customer_id': list(range(1, 21)),
'tenure_months': [2, 34, 5, 45, 12, 1, 60, 8, 24, 48,
3, 36, 7, 52, 15, 2, 42, 10, 30, 6],
'monthly_charges': [70, 45, 85, 30, 65, 90, 25, 75, 55, 35,
88, 40, 78, 28, 60, 92, 32, 72, 50, 82],
'contract': ['Month', 'Year', 'Month', 'TwoYear', 'Month', 'Month', 'TwoYear',
'Month', 'Year', 'TwoYear', 'Month', 'Year', 'Month', 'TwoYear',
'Year', 'Month', 'TwoYear', 'Month', 'Year', 'Month'],
'churned': [1, 0, 1, 0, 1, 1, 0, 1, 0, 0,
1, 0, 1, 0, 0, 1, 0, 1, 0, 1]
}
df = pd.DataFrame(data)
df_encoded = pd.get_dummies(df, columns=['contract'], drop_first=True)
feature_cols = ['tenure_months', 'monthly_charges', 'contract_TwoYear', 'contract_Year']
X = df_encoded[feature_cols]
y = df_encoded['churned']
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
model = LogisticRegression(random_state=42)
model.fit(X_scaled, y)
# Get churn probabilities and generate the risk report

More Churn Prediction exercises

All Python exercises · 50 practice problems · Practical Projects quiz