Sub topic 12
Clustering: Grouping Similar Examples
Clustering is the main unsupervised task. You give an algorithm a table of examples with no labels. It splits the examples into groups so that members of a group are more similar to each other than to members of other groups. This chapter assumes you know what features are, that unsupervised learning means working without labels, and basic NumPy and scikit-learn usage. Mean, variance, and Euclidean distance are used without further introduction.
What a cluster is, and what it is not
A cluster is a set of examples that the algorithm treats as similar. "Similar" is defined by two choices you make: how features are represented, and which distance or density rule the algorithm uses. Change either one and you get different clusters from the same data.
Clustering differs from classification in three ways:
- There are no ground-truth classes to match. The algorithm invents group IDs such as 0, 1, 2. These numbers have no meaning and can change between runs.
- No single answer is "correct". A customer dataset can be split into 3 groups or 12, and both can be useful.
- You cannot compute accuracy against labels in real work, because if you had labels you would probably use supervised learning.
Typical uses are customer segmentation, grouping similar documents, finding user behavior patterns, compressing images by reducing colors, and exploring a new dataset before choosing a model.
K-means: the working model
K-means is the standard starting point. You choose the number of clusters, k. The algorithm then repeats two steps until nothing changes:
- Assignment: give each example to the nearest of
kcentroids (points that represent cluster centers). - Update: move each centroid to the mean of the examples assigned to it.
The algorithm starts from initial centroids. It reaches a stable state because each step cannot increase the quantity it optimizes, the sum of squared distances from each example to its assigned centroid. This quantity is called inertia, or within-cluster sum of squares. K-means is a training loop with a loss function, like supervised learning. The difference is that the loss is defined on the data alone.
Running K-means
The iris measurements have three species, but we hide the labels and ask for three clusters.
from sklearn.datasets import load_iris
from sklearn.cluster import KMeans
X, _ = load_iris(return_X_y=True) # the labels are ignored
kmeans = KMeans(n_clusters=3, n_init=10, random_state=0)
kmeans.fit(X)
print(kmeans.labels_[:10])
print(kmeans.cluster_centers_)
print(kmeans.inertia_)Three attributes matter:
labels_holds the cluster ID of each training example.cluster_centers_has shape(3, 4), one centroid per cluster and one coordinate per feature. Reading these centroids is the quickest way to describe what each cluster means.inertia_is the loss value. Lower is tighter, but it always falls askgrows, so you cannot compare it across differentkvalues by itself.
n_init=10 runs the algorithm from ten different starting points and keeps the best result by inertia. This matters because the loop only finds a local optimum, and a poor start can give a poor split. random_state=0 makes the run repeatable.
To place a new example into an existing clustering, call kmeans.predict(new_rows). It assigns each row to its nearest centroid.
Scale your features first
K-means uses Euclidean distance, so a feature measured in large numbers dominates the distance. If one column is income in dollars and another is age in years, the clusters will mostly reflect income. Standardize first, which gives each feature mean 0 and standard deviation 1:
from sklearn.preprocessing import StandardScaler
X_scaled = StandardScaler().fit_transform(X)The iris features are all in centimeters, so scaling changes little there. On mixed-unit data it often changes the result completely.
Choosing k
The algorithm cannot choose k for you. Two common aids are described below.
| Method | What you compute | How to read it | Weakness |
|---|---|---|---|
| Elbow plot | Inertia for each `k` | Look for the `k` after which inertia stops dropping sharply | The bend is often not clear |
| Silhouette score | Mean silhouette over all examples, from -1 to 1 | Higher means examples sit closer to their own cluster than to the next nearest one | Favors round, similar-sized clusters, and costs more on large data |
This code computes both for several values of k:
from sklearn.datasets import load_iris
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
from sklearn.preprocessing import StandardScaler
X, _ = load_iris(return_X_y=True)
X_scaled = StandardScaler().fit_transform(X)
for k in range(2, 7):
km = KMeans(n_clusters=k, n_init=10, random_state=0).fit(X_scaled)
score = silhouette_score(X_scaled, km.labels_)
print(k, round(km.inertia_, 1), round(score, 3))Inertia falls at every step. The silhouette score on iris usually peaks at k=2, because one species is far from the other two and those two overlap. That is a useful lesson: the "best" number by a metric can disagree with the number you know is true. Treat these numbers as evidence and combine them with what the clusters will be used for. If a marketing team can only run four campaigns, k=4 may be the right answer even if k=3 scores slightly higher.
Failure modes of K-means
K-means makes assumptions about the shape of the data. When they fail, it still returns clusters without any warning.
- Non-spherical shapes. Centroids carve space into convex regions, so crescents, rings, and elongated groups get cut wrongly.
- Very different cluster sizes or densities. Examples at the edge of a large cluster can get pulled into a small neighbor.
- Outliers. A mean is sensitive to extreme points, so one far-away example can drag a centroid or claim a cluster of its own.
- Every example must belong somewhere. There is no "noise" label.
- Different results across starts. Use
n_initand a fixedrandom_statefor reproducibility. - High dimensions. Distances between points become less distinct as the number of features grows, so clusters become less meaningful. Reducing dimensions first often helps.
An alternative: density-based clustering
DBSCAN defines a cluster as a dense region separated from other dense regions by sparse space. It takes two parameters: eps, the neighborhood radius, and min_samples, how many neighbors make a point part of a dense region. It does not need k, it finds clusters of any shape, and it labels outliers as -1. Its weaknesses are sensitivity to eps and trouble when clusters have very different densities.
The two-moons dataset shows the contrast. Here we have the true labels only because the data is synthetic, so we can use the adjusted Rand index (ARI) to score agreement. ARI is 1 for perfect agreement and near 0 for random grouping.
from sklearn.datasets import make_moons
from sklearn.cluster import KMeans, DBSCAN
from sklearn.metrics import adjusted_rand_score
X, y_true = make_moons(n_samples=300, noise=0.05, random_state=0)
km_labels = KMeans(n_clusters=2, n_init=10, random_state=0).fit_predict(X)
db_labels = DBSCAN(eps=0.2, min_samples=5).fit_predict(X)
print("kmeans ARI:", round(adjusted_rand_score(y_true, km_labels), 3))
print("dbscan ARI:", round(adjusted_rand_score(y_true, db_labels), 3))K-means cuts both crescents with a straight boundary and scores low. DBSCAN follows each crescent and scores close to 1. On real data you rarely have such labels, so you would inspect clusters visually or by their summary statistics instead.
Other options exist, such as hierarchical (agglomerative) clustering, which builds a tree of merges, and Gaussian mixture models, which give soft membership probabilities. K-means and DBSCAN cover the two most common situations: compact groups and arbitrary shapes.
Evaluating clusters without labels
Without ground truth, you have three kinds of checks:
- Internal metrics, such as inertia and silhouette score. They measure compactness and separation, not usefulness.
- Stability. Re-run on a bootstrap sample or with a different seed. If the groups change a lot, they are probably not real structure.
- Profiling and downstream value. Compute per-cluster means of each feature and see whether the groups are interpretable and actionable. If you have labels for a small part of the data, compare clusters against them with ARI as a sanity check.
Common errors
- Forgetting to scale features, so one column decides the result.
- Treating cluster IDs as classes. Cluster 0 in one run may be cluster 2 in another.
- Picking
kfrom inertia alone, which always improves askgrows. - Fitting K-means on data that includes an ID column or a raw timestamp, which creates meaningless distance.
- Using K-means on categorical columns encoded as integers. Distance between category codes has no meaning.
Exercise
You run K-means with k=2 through k=8 on standardized customer data. Inertia decreases at every step, and the silhouette score is highest at k=3. Your manager wants to know whether k=8 is "more accurate" than k=3. What do you answer, and what two further checks would you run?
Show answer
Lower inertia at k=8 does not mean more accurate, because inertia always falls as k increases, and no ground-truth labels exist to measure accuracy against. The silhouette score favors k=3 for separation. Two further checks are (1) stability: refit with different random seeds or bootstrap samples and see whether the groups stay mostly the same, and (2) profiling: compute each cluster's mean feature values and see whether the groups are interpretable and useful for the business decision, such as how many segments can be acted on.
Exercise
A dataset contains two interleaved crescent-shaped groups. K-means with k=2 splits them badly. Name one algorithm that is better suited, name the parameter that replaces k, and say what label it gives to outliers.
Show answer
DBSCAN is better suited, because it groups dense regions of any shape. It has no k. The neighborhood radius eps (together with min_samples) controls how many clusters appear. It labels outliers as -1.