Rana Maninder Singh
Lesson 6 of 7ML Advanced

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

ResourceLink
PreviousCross-validation & GridSearch
NextChurn capstone
PrerequisitesFeature 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)
InputFeatures and labels (y)Features only
GoalPredict known targetDiscover structure
ExamplesChurn, fraud, revenue forecastSegments, anomalies
MetricAccuracy, F1, MAESilhouette, 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:

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

  1. Pick k cluster centres (centroids)
  2. Assign each customer to nearest centroid
  3. Move centroids to mean of assigned customers
  4. 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:

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 bends

WHY No single perfect k — combine elbow with interpretability.

WHEN Stakeholders can act on 3–6 segments, not 20 micro-clusters.

kTradeoff
Too lowBroad buckets, weak targeting
Too highOver-segmentation, tiny groups
Just rightNamed personas ops understands

Naming clusters for stakeholders

Example output interpretation (your numbers will differ):

ClusterProfileSuggested nameAction
0High spend, long tenureChampionsLoyalty rewards
1Low orders, newExplorersOnboarding offers
2High tickets, low spendAt-riskSupport outreach
3High churn rateDriftingWin-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

LimitationMitigation
Assumes roughly round clustersTry DBSCAN or GMM for odd shapes
Sensitive to scaleAlways StandardScaler
Sensitive to outliersCap extreme revenue or winsorise
No guaranteed global optimumIncrease n_init

Supervised + unsupervised together

Pipeline many teams use:

  1. K-means → segment label as new feature
  2. Random forest → churn prediction with cluster column

WHY Unsupervised structure can boost supervised models.

WHEN Heterogeneous customer base (metro vs tier-2 behaviour).


Essential commands

Command / actionWhat 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