Sub topic 1
What Clustering Does and What Counts as a Cluster
Clustering is an unsupervised learning method. It groups data points without a target label. A useful cluster contains points that are similar under a chosen distance measure and different from points in other clusters. “Useful” depends on the task. A customer grouping, for example, may use spending and visit frequency.
Prerequisites
This chapter assumes basic Python and NumPy, Euclidean distance, and familiarity with scikit-learn’s fit and predict style. You should also understand that unsupervised learning works without known answer labels.
Measuring Distance Between Points
For two points with features \(x\) and \(y\), Euclidean distance is:
\[ d(x,y)=\sqrt{\sumj(xj-y_j)^2} \]
Clustering algorithms use this distance, or another dissimilarity measure, to decide which points or groups are close. The feature representation therefore defines what “similar” means. Manhattan distance can be useful when differences add independently. Cosine distance focuses on direction rather than size, which is common for text vectors.
Scaling Features Before Clustering
Distance is sensitive to units. Suppose age ranges from 18 to 80 while annual income ranges from 20,000 to 200,000. Income will dominate Euclidean distance unless you scale the features.
Standardization subtracts each feature’s mean and divides by its standard deviation. Min-max scaling maps values to a fixed interval. Choose scaling based on the data and the meaning of extreme values.
import numpy as np
from sklearn.preprocessing import StandardScaler
from scipy.cluster.hierarchy import linkage
X = np.array([[25, 30_000], [40, 70_000], [42, 72_000]])
X_scaled = StandardScaler().fit_transform(X)
Z = linkage(X_scaled, method="ward")
print(Z.shape)Agglomerative Clustering: Merging from the Bottom Up
Agglomerative clustering starts with one cluster per point. It repeatedly merges the two closest clusters until one hierarchy remains. The hierarchy records every merge, so you can later choose a desired number of groups.
Linkage Criteria and the Clusters They Favor
Linkage defines the distance between two clusters.
| Linkage | Cluster distance | Typical effect |
|---|---|---|
| Single | Closest pair | Can create long chains |
| Complete | Farthest pair | Favors compact groups |
| Average | Mean pairwise distance | Balanced behavior |
| Ward | Increase in within-cluster variance | Favors similarly sized, round groups |
Ward linkage generally requires Euclidean features and is sensitive to scaling. The best choice depends on the geometry you expect, not only on a default setting.
Exercise
Why can unscaled income overwhelm age in Euclidean clustering?
Show answer
Income has much larger numerical differences, so it contributes more to the distance unless the features are scaled.