Module 12 · Scikit-learn: Building Real Models · Lesson 40 of 51

Pipelines and a churn classifier

Bundle preprocessing and model with Pipeline and ColumnTransformer so nothing leaks, train a logistic regression to predict member churn, and read the classification report and AUC.

In this lesson · about 45 minutes

  • Build a ColumnTransformer that scales numbers and one-hot encodes categories
  • Chain it with a model in a Pipeline and fit everything in one call
  • Evaluate a classifier with predict_proba, a classification report and ROC AUC

A churn model in one pipeline

Reading it

  • stratify=y in the split keeps the churn rate equal in train and test.
  • predict_proba gives the score; predict uses a fixed 0.5 threshold, which you can (and usually should) choose yourself, as in Module 11.
  • Logistic regression coefficients are on the log-odds scale: positive pushes towards churn. Because the numbers were standardised, sizes can be compared: a coefficient of 0.9 on complaints means one standard deviation more complaints multiplies the odds of churn by about e^0.9 ≈ 2.5.
  • handle_unknown="ignore" stops the encoder crashing if a new branch appears later.

Exercise

Build and score the pipeline

The split and the prep ColumnTransformer are ready. Build clf, a Pipeline of prep then LogisticRegression(max_iter=1000), fit it on the training data, and set auc to the test ROC AUC rounded to 3 decimals. Then set recall_at_03 to the test recall when you predict churn for scores of 0.3 or more, rounded to 3 decimals.

Code that runs before yours
import pandas as pd
import numpy as np
members = pd.read_csv("kc_members.csv")
from sklearn.model_selection import train_test_split
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from sklearn.linear_model import LogisticRegression
num = ["age", "tenure_months", "visits_90d", "avg_spend", "app_user", "complaints"]
cat = ["home_branch", "plan"]
X, y = members[num + cat], members["churned"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42, stratify=y)
prep = ColumnTransformer([("num", StandardScaler(), num), ("cat", OneHotEncoder(handle_unknown="ignore"), cat)])
from sklearn.metrics import roc_auc_score, recall_score

Check your understanding0 of 3 correct

Question 1

1.Main benefit of a Pipeline?

Question 2

2.stratify=y in train_test_split…

Question 3

3.A positive logistic coefficient on complaints means…

Quiz score: 0 of 3

Exercises solved: 0 of 1

Tip: answer every quiz question correctly first.

Written by Noviq Academy in its own words. Kettle & Crumb and all its data are made up for teaching; any resemblance to a real business is a coincidence. Python runs in your browser with Pyodide, so results can differ slightly from your own computer. Power BI, Tableau and other product names belong to their owners. Read-aloud uses your device's built-in voices.