Clustering

Discover natural groups in data without labels.

The Big Question

Most algorithms so far learned from labelled examples. The model saw inputs and correct answers, then learned to predict those answers.

But many real datasets have no labels. Imagine collecting thousands of restaurant visits with price, distance, waiting time, calories, cuisine, and atmosphere, but no record of whether Jessie liked the restaurant.

Can we still discover useful structure? Clustering says yes.

Core Intuition

A cluster is a group of examples that are more similar to one another than to the rest of the dataset. If restaurant visits form three visible groups, those groups might later be interpreted as fast food, casual dining, and fine dining.

The algorithm does not know those names. It only sees similarity. Humans interpret the meaning afterwards.

Customers

Group people by spending and purchase history.

Biology

Find possible cell types from gene expression.

Fraud

Flag points that do not belong to any normal group.

Interactive Demo

K-Means lab
123
Within-cluster loss
4349

Each iteration assigns points to the nearest centroid, then moves each centroid to the mean of its assigned points.

Centroid 1
(20.0, 22.0)
Centroid 2
(74.0, 28.0)
Centroid 3
(50.0, 74.0)

Increase the iteration count to watch K-Means alternate between assigning points and moving centroids.

Mathematics

K-Means Algorithm

K-Means is the most common clustering algorithm. Choose a number of clusters KK, place KK centroids, assign each point to its nearest centroid, move centroids to the mean of assigned points, and repeat.

Assignment step

Given current centroids, assign every point to the nearest one.

Update step

Given assignments, move each centroid to the average of its points.

Repeat

Continue until assignments stop changing or a maximum iteration count is reached.

Interpret

Name and inspect clusters after the algorithm finishes.

Distance

K-Means usually uses Euclidean distance. For two points x=(x1,x2)x=(x_1,x_2) and y=(y1,y2)y=(y_1,y_2):

d(x,y)=(x1y1)2+(x2y2)2d(x,y)=\sqrt{(x_1-y_1)^2+(x_2-y_2)^2}

Objective Function

K-Means tries to minimize total within-cluster squared distance:

J=i=1nxiμc(i)2J=\sum_{i=1}^{n}\|x_i-\mu_{c(i)}\|^2

Here xix_i is a data point, μc(i)\mu_{c(i)} is the centroid of its assigned cluster, and c(i)c(i) is the cluster assignment.

Why It Works

Each assignment step chooses the nearest centroid, so the objective cannot increase. Each update step moves the centroid to the mean, which is the point that minimizes squared distance to assigned points. This also cannot increase the objective.

Because the objective decreases or stays unchanged each iteration, K-Means eventually converges. It may converge to a local optimum, so different initializations can produce different clusters.

Choosing K

Choosing the number of clusters is one of the hard parts. The elbow method plots KK against within-cluster sum of squares and looks for the point where improvements begin to level off.

Silhouette score compares how close a point is to its own cluster versus nearby clusters. Higher values usually indicate cleaner separation.

Limitations

K-Means works best when clusters are roughly spherical, similarly sized, and well separated. It struggles with irregular shapes, different densities, outliers, and unscaled features.

Other Clustering Algorithms

Hierarchical

Builds a tree of nested clusters and can help when K is unknown.

DBSCAN

Finds dense regions, handles irregular shapes, and can mark outliers.

Gaussian mixtures

Uses soft assignments, so a point can partially belong to multiple clusters.

Clustering Versus Classification

QuestionClassificationClustering
LabelsProvided during trainingNot provided
GoalPredict known classesDiscover unknown groups
Learning typeSupervisedUnsupervised
EvaluationCompare to ground truth labelsInspect structure, separation, usefulness

Implementation

This NumPy implementation follows the two-step K-Means loop: assign to nearest centroid, then recompute centroids as means.

import numpy as np

def kmeans(X, k, max_iter=100, seed=0):
    rng = np.random.default_rng(seed)
    centroids = X[rng.choice(len(X), size=k, replace=False)]

    for _ in range(max_iter):
        distances = np.linalg.norm(
            X[:, None, :] - centroids[None, :, :],
            axis=2,
        )
        labels = np.argmin(distances, axis=1)

        new_centroids = np.array([
            X[labels == cluster].mean(axis=0)
            if np.any(labels == cluster)
            else centroids[cluster]
            for cluster in range(k)
        ])

        if np.allclose(new_centroids, centroids):
            break

        centroids = new_centroids

    objective = np.sum((X - centroids[labels]) ** 2)
    return labels, centroids, objective

Interview Discussion

What is clustering?

Clustering is unsupervised learning that groups examples by similarity without using labels.

How does K-Means work?

It alternates between assigning points to nearest centroids and moving each centroid to the mean of assigned points.

Why does the centroid move to the mean?

For squared distance, the mean minimizes the total squared distance to the points in that cluster.

How do you choose K?

Use domain knowledge, elbow plots, silhouette scores, stability checks, and whether the clusters are useful for the downstream task.

When would DBSCAN be better than K-Means?

When clusters have irregular shapes, there are outliers, or you do not want to choose K directly.

Active Recall

1. What objective does K-Means optimize?

2. Why does each iteration reduce the objective?

3. Why does the centroid equal the mean?

4. What assumptions does K-Means make about cluster shape?

5. When would DBSCAN outperform K-Means?

6. Why can clustering accuracy not be measured the same way as classification accuracy?

Common Mistakes

  • Thinking clusters always correspond to meaningful categories.
  • Assuming K-Means finds the global optimum.
  • Forgetting to standardize features.
  • Using K-Means for non-spherical clusters.
  • Assuming the centroid must be an actual data point.

Connection To Perceptron

PCA compressed data by finding directions of maximum variance. Clustering goes one step further: it tries to uncover hidden groups. This completes the Representation section. The next major question is how to learn increasingly powerful representations automatically, which begins Deep Learning.