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

Clustering, saving and explaining your model

Segment members with KMeans and silhouette scores, save a trained pipeline with joblib, score new members, and write a one-page model card.

In this lesson · about 40 minutes

  • Segment customers with scikit-learn's KMeans and judge k with silhouette scores
  • Save and reload a trained pipeline and score new rows
  • Write a model card that a manager can read

Member segments with KMeans

The silhouette score (−1 to 1) asks: is each point much closer to its own cluster than to the next one? Higher is better. Then name the segments from their averages, for example "loyal regulars", "big occasional spenders", "new and drifting".

Saving a model

import joblib
joblib.dump(clf, "churn_model.joblib")        # the whole pipeline, preprocessing included
model = joblib.load("churn_model.joblib")
model.predict_proba(new_members)[:, 1]

Save the pipeline, not just the model, so new data gets the same scaling and encoding. Record the library versions too: a model saved with one scikit-learn version may not load in another.

The model card

PurposeRank members by churn risk each Monday for the retention team.
Data800 members, features as of the scoring date; target = churned in the next 60 days.
ModelLogistic regression pipeline (scaled numbers, one-hot branch and plan).
PerformanceTest AUC and recall/precision at the chosen threshold, with the baseline.
LimitsNot tested on members under 3 months; drift expected after price changes.
Fairness and useOnly used to offer perks, never to deny service; check error rates by age group.
Owner and retrainingData team; retrain monthly; alert if weekly AUC drops below 0.7.

Exercise

Pick k with the silhouette

Standardise visits_90d and avg_spend, then for k from 2 to 6 fit KMeans(n_clusters=k, n_init=10, random_state=0). Set scores to a dict of k → silhouette score rounded to 3 decimals, and best_k to the k with the highest score.

Code that runs before yours
import pandas as pd
import numpy as np
members = pd.read_csv("kc_members.csv")
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score

Exercise

Save, reload and score new members

Fit clf (the prep + LogisticRegression(max_iter=1000) pipeline) on the training data, save it with joblib.dump to "churn_model.joblib", load it back as loaded, and set risk to the churn probabilities of the two new_members, rounded to 3 decimals, as a list.

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)])
import joblib
new_members = pd.DataFrame([
    {"age": 24, "tenure_months": 2, "visits_90d": 1, "avg_spend": 5.5, "app_user": 0, "complaints": 2, "home_branch": "Airport", "plan": "Free"},
    {"age": 41, "tenure_months": 30, "visits_90d": 18, "avg_spend": 11.0, "app_user": 1, "complaints": 0, "home_branch": "Downtown", "plan": "Plus"},
])

Write the model card for your churn model.

Consider these questions and write down your thoughts. What you write stays on this device.

Flashcards

Module 12 flashcards

0 of 11 known

Say the answer out loud, flip the card, then be honest: cards you miss come back at the end.

11 left in the deck

Practice exam

Module 12 checkpoint

12 questions, 15 minutes.

  • 12 questions · 15 minutes
  • No feedback until you submit. Flag questions to come back to them.
  • Aim for 85% or better before you move on. The real exam's 750 out of 900 is roughly 80–83%.

Exercises solved: 0 of 2

Tip: solve each exercise first. Press Check to test your code.

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.