Editor

Build a Confusion Matrix

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

From the lesson: Step 6: Evaluate with a Confusion Matrix

Accuracy alone can be misleading. If 90% of customers don't churn, a model that always predicts "no churn" gets 90% accuracy but is useless. A confusion matrix breaks down predictions into four categories: true positives, true negatives, false positives, and false negatives.

Read this part of the lesson

Using the trained model from the previous step, generate predictions and build a confusion matrix. Print:

1. The confusion matrix using confusion_matrix(y, predictions)

2. The classification report using classification_report(y, predictions)

Label the output: "Confusion Matrix:" and "Classification Report:"

import pandas as pd
import numpy as np
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import confusion_matrix, classification_report
data = {
'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)
# Generate predictions and print confusion matrix + classification report

More Churn Prediction exercises

All Python exercises · 50 practice problems · Practical Projects quiz