Unsupervised Learning: Clustering

Machine Learning Fundamentals

Chapter 9 · Unsupervised Learning: Clustering

ml1-1 named supervised and unsupervised learning as this course's own two branches — every chapter since has been supervised, working from a known, provided answer (price, left_company). This chapter is the other branch, made concrete rather than abstract: the exact same datasets, with every label deliberately removed.

What Changes When There's No Label

Every technique since ml1-3 learned by comparing its own predictions against a known, correct answer during training. Clustering has no such answer to learn from at all — it's asked only to group similar data points together, discovering whatever structure exists on its own, with nobody ever telling it what the "right" groups are.

K-Means — The Algorithm, Step by Step

  • Choose k, the number of clusters, in advance.
  • Randomly place k initial centroids (cluster centers).
  • Assign every data point to its nearest centroid.
  • Recompute each centroid as the average position of every point now assigned to it.
  • Repeat steps 3–4 until the centroids stop moving meaningfully.
  • A genuinely different fitting mechanism than anything earlier in this course: no least-squares fit against a known target (ml1-3), no entropy-driven split search against known labels (ml1-7) — k-means iteratively refines its own evolving guess about where the clusters are, with nothing external to check itself against.

    Choosing k — The Elbow Method

    Unlike supervised learning, where the number of real classes is simply given (ml1-5's own two — Yes/No), nothing hands k to this chapter directly. Plotting inertia (the total squared distance from each point to its own assigned centroid) against increasing values of k always trends downward — more clusters always let points sit closer to their own center — but with sharply diminishing returns past a certain point. The "elbow" — where adding another cluster stops meaningfully reducing inertia — is a reasonable, practical choice for k.

    A heuristic, not a definitive answer
    Real data often doesn't have one obvious elbow — the same honest, judgment-call territory ds1-4's own cleaning decisions and imgai1-4's own --stylize tuning both occupied. The elbow method narrows the choice; it doesn't remove the judgment call entirely.

    Running It for Real — ds1-9's Own Used-Car Data, Unlabeled

    from sklearn.cluster import KMeans
    from sklearn.preprocessing import StandardScaler
    
    X = df[["mileage", "year", "price"]]
    X_scaled = StandardScaler().fit_transform(X)
    
    kmeans = KMeans(n_clusters=3, random_state=42)
    clusters = kmeans.fit_predict(X_scaled)
    Illustrative result — ds1-9's used cars, ml1-3's own dataset, no labels this time
    Three clusters plausibly emerge roughly along an age gradient: newer, low-mileage, higher-price cars in one group; older, high-mileage, lower-price cars in another; a middle group between them. Nobody told the algorithm "year" mattered or how to weight it — it discovered this structure purely from how the three numeric features happened to cluster together, on the exact same rows ml1-3 already fit a supervised regression on.

    Running It on ds1-10's Own Employees — A Genuinely New Finding

    X = df[["age", "years_at_company", "salary"]]
    X_scaled = StandardScaler().fit_transform(X)
    clusters = KMeans(n_clusters=3, random_state=42).fit_predict(X_scaled)
    Illustrative result — a pattern supervised learning was never set up to look for
    One cluster plausibly emerges with unusually long tenure paired with comparatively low salary — long-serving employees who haven't been paid in step with their own loyalty. ml1-5's own logistic regression could only ever answer the specific question it was given (does salary predict attrition?). This chapter's clustering wasn't given a question at all — it surfaced a group nobody had explicitly asked about, which is exactly what unsupervised learning is genuinely for.

    Why Scaling Isn't Optional Here

    ml1-3 standardized features so coefficient sizes could be compared fairly. K-means needs standardization for a stricter reason: the algorithm's own "nearest centroid" step is a literal distance calculation. Left unscaled, salary (tens of thousands) would swamp years_at_company (single digits) in every distance computation, and the resulting clusters would essentially just be salary bands wearing three other features' names. Scaling here isn't a nicety for readability — it determines whether the clustering result means anything at all.

    Crisp Assignment — And a Preview of ch10

    Every point in k-means belongs to exactly one cluster, fully — a crisp assignment, with no notion of "70% in this cluster, 30% in that one." ml1-10's own Fuzzy Logic chapter picks up exactly here, with a system built specifically around partial, graded membership instead.

    Hands-On Exercises

    Exercise 1

    Explain, using this chapter's own five-step k-means description, why this algorithm's own fitting process is described as "genuinely different" from ml1-3's least-squares fitting or ml1-7's entropy-driven splits.

    📄 View solution
    Exercise 2

    Explain why this chapter says clustering on ds1-10's own employee data surfaced "a genuinely new finding," specifically contrasting what ml1-5's own supervised model could and couldn't have found on its own.

    📄 View solution
    Exercise 3

    Explain why this chapter treats feature scaling as stricter for k-means than ml1-3's own scaling requirement for regression coefficients, using this chapter's own reasoning about distance calculations.

    📄 View solution

    Chapter 9 Quick Reference

    • Unsupervised — no known answer to train against; the algorithm discovers structure entirely on its own
    • K-means — choose k, place centroids, assign, recompute, repeat to convergence — no external target to fit against
    • Elbow method — inertia vs. k, diminishing returns mark a reasonable k; a heuristic, not a definitive answer
    • Re-run on ds1-9/ds1-10's own data with labels removed — ml1-1's abstract supervised/unsupervised distinction, made concrete
    • Clustering surfaced a pattern (underpaid long-tenure employees) ml1-5's own supervised model was never even asked to look for
    • Scaling is a strict necessity here — k-means computes real distances, unlike ml1-3's own comparison-only standardization
    • K-means gives crisp (all-or-nothing) cluster assignment — Next chapter: Fuzzy Logic — Beyond Crisp Boolean Rules