Sub topic 12
Clustering: grouping similar examples
Clustering is an unsupervised task. You give the algorithm unlabeled examples, and it groups them so that examples in the same group are more similar to each other than to examples in other groups. This chapter assumes you know what features are, how a NumPy array of examples is laid out (rows are examples, columns are features), and the idea of distance between points.
The working model
A clustering algorithm has no labels to check against. It uses only the geometry of the features. Two choices shape the result:
- A definition of similarity, most often Euclidean distance between feature vectors.
- The number of groups, or a rule for deciding it.
The output is a cluster assignment for each example. The cluster numbers are arbitrary names, not meaningful categories. Cluster 0 on one run may be cluster 2 on another.
K-means
K-means is the standard starting point. You choose k, the number of clusters. The algorithm then repeats two steps:
- Assign each example to the nearest of k center points, called centroids.
- Move each centroid to the mean of the examples assigned to it.
It stops when assignments no longer change. The quantity it minimizes is the sum of squared distances from each example to its centroid. This is called inertia.
Running K-means on iris
The iris data has true species labels, but this code discards them. The algorithm sees only the four measurements.
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_)labels_ holds the cluster index for each example. cluster_centers_ is a 3-by-4 array: one centroid per cluster, with one coordinate per feature. Setting n_init=10 runs the algorithm from ten random starts and keeps the best result by inertia. Setting random_state makes the run repeatable.
Common errors
- Unscaled features. Distance is dominated by features with large numeric ranges. If one feature is in thousands and another is between 0 and 1, the small one barely matters. Standardize features first, for example with
StandardScaler. Iris features are all in centimeters, so it is safe to skip here. - Picking k without checking. K-means always returns k clusters, even when the data has no such structure. Compare inertia across several values of k and look for an "elbow" where improvement slows. You can also compute the silhouette score (
sklearn.metrics.silhouette_score), which ranges from -1 to 1. Higher values mean tighter, better-separated clusters. - Assuming round clusters. K-means favors compact, similarly sized, roughly spherical groups. It splits elongated or ring-shaped clusters badly. Algorithms such as DBSCAN, which groups dense regions, handle those shapes better.
- Treating clusters as ground truth. A cluster is a statement about similarity in the chosen features. Whether it matches a real category is something you must judge, often with domain knowledge.
- Ignoring initialization. A single random start can land in a poor solution. Keep
n_initabove 1.
Checking the result
Without labels, you evaluate by inspection. Look at the centroids and ask whether each one describes a sensible group. Plot two features colored by cluster. Check cluster sizes, since a cluster with one or two members often marks outliers. Stability is another test: if different random seeds give very different groupings, the structure is weak.
Exercise
You run K-means on a table with two features: annual income in dollars (range 20,000 to 200,000) and age in years (range 18 to 80). The clusters appear to split people almost entirely by income. What is the likely cause, and what is the fix?
Show answer
Euclidean distance is dominated by income because its numeric range is far larger than age's. Standardize both features, for example with StandardScaler, before fitting K-means so each contributes comparably to the distance.
Exercise
Why can K-means with k=5 return five clusters on data that contains only one natural group?
Show answer
K-means always partitions the data into exactly k groups. It does not test whether the structure exists, so it splits a single group into pieces. Use inertia, silhouette scores, and inspection to judge whether the chosen k is justified.