K-Means Clustering — Supervised vs Unsupervised Learning
Lesson opener
In one line: Supervised vs unsupervised learning - labels vs patterns.
Why it matters: Not every business question has a label column - "who are our best customers?" is clustering, not classification.
Before this lesson: Feature engineering / Customer analytics
Before you start
| Resource | Link |
|---|---|
| Previous | Cross-validation & GridSearch |
| Next | Churn capstone |
| Prerequisites | Feature engineering, Customer analytics |
| Time | ~55 minutes |
What you will learn
- Supervised vs unsupervised learning — labels vs patterns
- How K-means groups customers by similarity
- Choosing k and interpreting clusters for marketing
- RFM segmentation callback to Customer analytics
Supervised vs unsupervised (recap)
You met all three learning types in What is machine learning?. This lesson focuses on unsupervised clustering — no churn label, only features.
| Supervised (earlier lessons) | Unsupervised (this lesson) | |
|---|---|---|
| Input | Features and labels (y) | Features only |
| Goal | Predict known target | Discover structure |
| Examples | Churn, fraud, revenue forecast | Segments, anomalies |
| Metric | Accuracy, F1, MAE | Silhouette, business interpretability |
| sklearn | .fit(X, y) | .fit(X) |
WHY Not every business question has a label column — "who are our best customers?" is clustering, not classification.
WHEN Marketing wants segments before building a churn model, or to enrich features.
Indian workplace example: A Delhi fashion marketplace has no "churn" flag yet but wants cohorts for WhatsApp campaigns. K-means on recency, frequency, and spend creates actionable groups.
RFM callback — Customer analytics
From Customer analytics, RFM scores:
- Recency — days since last purchase
- Frequency — order count
- Monetary — total spend
Rule-based RFM uses fixed thresholds ("R > 30 days = at risk"). K-means learns clusters from data — complementary, not a replacement.
WHY Combine domain RFM thinking with algorithmic grouping.
WHEN Thousands of customers — manual RFM buckets get arbitrary.
How K-means works
- Pick k cluster centres (centroids)
- Assign each customer to nearest centroid
- Move centroids to mean of assigned customers
- Repeat until stable
WHY Simple, fast, works well on scaled numeric features.
WHEN Roughly spherical clusters in feature space — good starting point for segmentation.
sklearn — customer segments
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import KMeans
df = pd.read_csv("data/customers.csv")
# RFM-style features
X = df[["tenure_months", "total_orders", "total_revenue", "monthly_spend"]].copy()
X["recency_proxy"] = 60 - df["tenure_months"].clip(upper=60) # illustrative
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
kmeans = KMeans(n_clusters=4, random_state=42, n_init=10)
df["cluster"] = kmeans.fit_predict(X_scaled)
profile = df.groupby("cluster")[["tenure_months", "total_orders", "monthly_spend", "churned"]].mean()
print(profile.round(2))Breaking it down:
StandardScaler— critical; K-means uses Euclidean distancen_clusters=4— business-friendly number (Champions, Loyal, At-risk, New)n_init=10— multiple random starts, pick best inertia- Profile clusters with mean churn — validate business sense
Use this when: CRM needs segment labels for campaign personalisation.
Choosing k — elbow method
Inertia = total within-cluster sum of squares — drops as k increases.
inertias = []
for k in range(2, 9):
km = KMeans(n_clusters=k, random_state=42, n_init=10)
km.fit(X_scaled)
inertias.append(km.inertia_)
# Plot k vs inertia — look for "elbow" where curve bendsWHY No single perfect k — combine elbow with interpretability.
WHEN Stakeholders can act on 3–6 segments, not 20 micro-clusters.
| k | Tradeoff |
|---|---|
| Too low | Broad buckets, weak targeting |
| Too high | Over-segmentation, tiny groups |
| Just right | Named personas ops understands |
Naming clusters for stakeholders
Example output interpretation (your numbers will differ):
| Cluster | Profile | Suggested name | Action |
|---|---|---|---|
| 0 | High spend, long tenure | Champions | Loyalty rewards |
| 1 | Low orders, new | Explorers | Onboarding offers |
| 2 | High tickets, low spend | At-risk | Support outreach |
| 3 | High churn rate | Drifting | Win-back before churn model |
WHY Data science delivers when marketing recognises the segment names.
WHEN Present clusters with average RFM per group, not just "Cluster 2."
K-means limitations
| Limitation | Mitigation |
|---|---|
| Assumes roughly round clusters | Try DBSCAN or GMM for odd shapes |
| Sensitive to scale | Always StandardScaler |
| Sensitive to outliers | Cap extreme revenue or winsorise |
| No guaranteed global optimum | Increase n_init |
Supervised + unsupervised together
Pipeline many teams use:
- K-means → segment label as new feature
- Random forest → churn prediction with
clustercolumn
WHY Unsupervised structure can boost supervised models.
WHEN Heterogeneous customer base (metro vs tier-2 behaviour).
Essential commands
| Command / action | What it does |
|---|---|
KMeans(n_clusters=4, n_init=10) | Partition into k groups |
fit_predict(X_scaled) | Assign cluster per row |
cluster_centers_ | Centroid coordinates (scaled space) |
groupby("cluster").mean() | Business profiling |
Practice
Do this now: Cluster customers.csv into 4 groups on RFM-style features. Name each cluster for a Mumbai marketing lead. Compare mean churned per cluster — does one cluster look like your RFM at-risk segment?
Checklist
- [ ] I can contrast supervised (y) vs unsupervised (no y)
- [ ] Features scaled before K-means
- [ ] Clusters profiled with business-readable names
- [ ] Connected segmentation to RFM from Customer analytics
- [ ] Next: Churn capstone