Sub topic 1
What clustering is and where k-means fits
Prerequisites
This chapter assumes you know the following:
- Basic Python and NumPy array operations.
- The mean and Euclidean distance between vectors.
- Feature matrices, where rows are samples and columns are features.
- The basic idea of supervised versus unsupervised learning.
Clustering as unsupervised learning
Clustering groups samples so that samples in the same group are more similar to each other than to samples in other groups. The data has no labels. The algorithm only sees a feature matrix X with shape (n_samples, n_features) and must find structure on its own.
This is the main difference from classification:
| Row | Classification | Clustering |
|---|---|---|
| Learning type | Supervised | Unsupervised |
| Training data | Features and known labels | Features only |
| Output | Predicted label from a fixed set | A group index with no built-in meaning |
| Evaluation | Compare predictions to true labels | No ground truth, so you judge by internal measures and by usefulness |
A classifier learns to reproduce labels that someone supplied. A clustering algorithm proposes groups. The group numbers are arbitrary. Cluster 0 in one run may be cluster 2 in another, and neither number says what the group means. You decide that by inspecting the members.
Common uses include customer segmentation, grouping similar documents, compressing colors in an image, and exploring a dataset before building a model.
Where k-means fits
There are many clustering families. Some build a hierarchy of merges. Some find dense regions. Some fit probability distributions. K-means belongs to the family of centroid-based (or partitioning) methods. Each cluster is summarized by one point, its centroid, which is the mean of the points in the cluster.
K-means makes these commitments:
- You choose the number of clusters,
k, before running it. - Every point belongs to exactly one cluster (a hard assignment).
- A point belongs to the cluster whose centroid is nearest in Euclidean distance.
- The best clustering is the one with the smallest total squared distance from points to their centroids.
Those commitments make k-means fast and simple. They also decide where it fails, which a later chapter covers.
The idea in one picture
K-means alternates between two steps. Given the current centroids, it assigns each point to the nearest one. Given the current assignments, it moves each centroid to the mean of its points. It repeats until nothing changes.
This chapter only introduces the loop. Later chapters define the objective it minimizes, trace each step in code, and explain why it stops.
A first look at the data
Clustering starts with a feature matrix. The example below generates three groups of 2-D points, then discards the true group labels so the data looks like an unlabeled problem.
import numpy as np
from sklearn.datasets import make_blobs
X, true_labels = make_blobs(n_samples=300, centers=3, cluster_std=1.0, random_state=42)
print(X.shape) # (300, 2): 300 samples, 2 features
print(X[:3].round(2)) # first three rows
print(np.bincount(true_labels)) # group sizes, which a real problem would not give youIn real work you would not have true_labels. Here they exist only so you can later check that k-means recovers the groups. The point to take away is the shape: each row is one sample, and each cluster is a set of rows.
What you get back
A fitted clustering gives you two things:
- A label for each row, an integer from
0tok - 1. - A centroid for each cluster, a vector with
n_featuresentries.
Labels say which group a sample is in. Centroids describe what a typical member looks like. In a customer segmentation, the centroid of one cluster might show high spend and low visit frequency, and that description is how you name the segment.
Common mistakes at this stage
- Treating cluster numbers as meaningful. They are only identifiers and can change between runs.
- Assuming clusters exist. K-means will split any data into
kgroups, even uniform random noise. A result is not evidence that natural groups are present. - Comparing cluster labels to true labels directly. Because the numbering is arbitrary, a match must allow for any relabeling.
- Picking
kby habit. The algorithm cannot tell you whether three clusters is right. Choosingkhas its own chapter.
Check your understanding
Exercise
A teammate runs k-means with k=3 on customer data and reports that "cluster 1 is the high-value customers" because that cluster had the largest index in an earlier run. What is wrong with this claim?
Show answer
Cluster indices are arbitrary. Re-running the algorithm, or even changing the random seed, can assign different numbers to the same group. The meaning of a cluster has to come from inspecting its members or its centroid, for example by checking average spend, and not from its index.
Exercise
Name two ways clustering differs from classification, and one property k-means requires you to decide in advance.
Show answer
Clustering uses unlabeled data and produces group indices with no inherent meaning, while classification trains on labeled data and predicts labels from a fixed set. Clustering also has no ground truth to compare against. K-means requires you to choose the number of clusters, k, before running it.