Skip to content
GenAI Learn/The Classical ML Toolbox
Browsing as a guest. Sign in to save your progress and earn XP as you complete chapters.

Clustering & Dimensionality Reduction, in Practice

6 min read

You'll learn to

  • -Understand k-means as a concrete, widely used clustering algorithm
  • -Implement k-means clustering from scratch and watch it converge
  • -Understand PCA as a concrete, widely used dimensionality reduction technique

The unsupervised learning chapter introduced clustering and dimensionality reduction conceptually. This one gives each a concrete, standard algorithm, so the idea stops being abstract.

K-Means: Clustering by Repeatedly Averaging

K-means clustering works in a simple loop. Pick K starting points, called centroids. Assign every example to whichever centroid it is closest to. Move each centroid to the average position of the examples now assigned to it. Repeat this assign-then-average cycle until the centroids stop moving much. The result is K clusters, each gathered around its own centroid.

K-Means Objective
minimize Σₖ Σ_{x ∈ Cₖ} ‖x − μₖ‖²
For each cluster k, sum the squared distance from every point x in that cluster to its centroid μₖ, then sum across all clusters. K-means' assign-then-average loop is a direct, greedy way of reducing this quantity. It is itself a form of optimization, just like gradient descent, only with a different update rule.
K-means clustering (k=2), from scratch

You have to choose K, the number of clusters, ahead of time, and the right number is often genuinely unclear. Practitioners commonly try several values of K and look for the point where adding more clusters stops meaningfully improving the fit, sometimes called the elbow method.

PCA: Compressing Dimensions Without Losing the Point

Principal Component Analysis, or PCA, is the standard dimensionality reduction technique. It finds new, synthetic dimensions, each one a combination of the original features, ordered so the first new dimension captures as much of the data's variation as possible, the second captures as much of what is left, and so on. Keeping only the first few of these new dimensions often preserves most of the meaningful structure in the data while discarding the rest.

  • -K-means answers: which group does this example belong to?
  • -PCA answers: what are the few dimensions that actually matter most in this data?

Both techniques show up constantly as a first exploratory step. Clustering can reveal whether natural customer segments exist before you design a targeting strategy, and PCA can compress a dataset down to two or three dimensions just so a human can actually plot and look at it.

Interview Signal is part of Pro

See a real weak answer next to a real strong one for this exact topic.

Quiz is part of Pro

Test what you just read with a short quiz, and bank the XP.

ScaleDojo Logo
Initializing ScaleDojo