Python Master Course V2 — 137. Clustering, Dimensionality Reduction and Validation
Purpose and learning outcomes
Clustering and dimensionality reduction can reveal patterns, compress measurements, and support exploration. They can also create persuasive pictures of structure that is unstable or irrelevant. This lesson uses generated points with known construction to examine scaling, principal components, k-means, and a case where the algorithm’s geometry is a poor match.
- Scale data before distance-based methods
- Apply PCA and k-means and interpret their assumptions
- Evaluate cluster stability without inventing ground-truth meaning
Prerequisites: 122: linear algebra; 132: scaling; 136: evaluation design.
Environment and run order
Use a dedicated Python 3.11 or 3.12 virtual environment. These exercises use local synthetic or bundled data; no account, API key, or dataset download is needed. The shell commands install free packages. Run the Python blocks in order in one lesson file; worked solutions continue from that file unless stated otherwise.
Shell
python -m venv .venv
# macOS/Linux: source .venv/bin/activate
# Windows PowerShell: .venv\Scripts\Activate.ps1
python -m pip install numpy pandas scikit-learn matplotlib joblib
python -m pip freeze > requirements-observed.txt
Understand the model and the evidence
Distance is a modeling choice
K-means minimizes the sum of squared distances from observations to assigned cluster centers. The number of centers k must be chosen. When one feature is measured in thousands and another in tenths, Euclidean distance is dominated by the larger scale. Standardizing changes the question to differences measured in training standard deviations. That may be useful, but units and domain meaning should guide the choice rather than a universal instruction to scale everything.
PCA finds directions of variance
Principal component analysis constructs orthogonal directions that explain decreasing amounts of variation in centered data. A two-dimensional projection can simplify visualization, but high explained variance is not the same as relevance to a later target. A low-variance direction can be essential for a particular task. PCA is a fitted transformation: training determines the directions and held-out rows are projected using those directions unchanged.
K-means prefers compact distance-based partitions
The algorithm alternates assigning points to centers and moving centers to assigned means. Different initial centers may lead to different local solutions. n_init=10 explicitly tries multiple initializations. It is well suited to some compact roughly spherical groups in the chosen geometry, but curved or elongated structures can be split in misleading ways. Cluster numbers are arbitrary identifiers, not ordered categories.
Validation without semantic labels
Silhouette score compares within-cluster and nearest-other-cluster distances; larger values indicate separation under that geometry. It can favor an unhelpful partition and is undefined in degenerate cases such as a single cluster. Adjusted Rand index compares two partitions while ignoring label permutations, making it useful for a simple stability check. Stability says a method repeatedly finds a pattern; it does not prove that pattern corresponds to meaningful real-world groups.
Incremental worked example
1. Fit the representation on development points
We generate four-dimensional blobs, reserve held-out points, and learn scaling and PCA on training data only. This tests how a representation transfers to new points rather than letting the visualization learn every displayed observation.
Python
import numpy as np
from sklearn.datasets import make_blobs, make_moons
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score, adjusted_rand_score
X, generated_labels = make_blobs(n_samples=360, centers=3, n_features=4,
cluster_std=1.4, random_state=37)
Xr, Xv = train_test_split(X, test_size=0.25, random_state=37)
scaler = StandardScaler().fit(Xr)
Zr, Zv = scaler.transform(Xr), scaler.transform(Xv)
pca = PCA(n_components=2).fit(Zr)
projection = pca.transform(Zv)
print("projection shape", projection.shape)
print("explained variance", pca.explained_variance_ratio_)
2. Compare cluster counts, seeds, and a difficult geometry
We cluster the standardized original four-dimensional measurements, not the two-dimensional display coordinates. This avoids silently changing the clustering problem to match a plot. The final moon example is intentionally adversarial to compact spherical partitions.
Python
for k in [2, 3, 4]:
model = KMeans(n_clusters=k, n_init=10, random_state=37).fit(Zr)
labels = model.predict(Zv)
if 1 < len(np.unique(labels)) < len(labels):
print("k", k, "validation silhouette", silhouette_score(Zv, labels))
a = KMeans(n_clusters=3, n_init=10, random_state=1).fit(Zr).predict(Zv)
b = KMeans(n_clusters=3, n_init=10, random_state=2).fit(Zr).predict(Zv)
print("seed agreement ARI", adjusted_rand_score(a, b))
moon_X, moon_truth = make_moons(n_samples=240, noise=0.06, random_state=37)
moon_Z = StandardScaler().fit_transform(moon_X)
moon_labels = KMeans(n_clusters=2, n_init=10, random_state=37).fit_predict(moon_Z)
print("moon agreement with generated groups", adjusted_rand_score(moon_truth, moon_labels))
Expected output / interpretation
projection shape (90, 2)
Explained-variance fractions, silhouette values, and agreement scores are runtime measurements.
The moon example is exploratory; its full-data scaling is not a held-out generalization claim.
Guided lab and acceptance criteria
- Plot the validation PCA coordinates colored by the three-cluster predictions. Label the axes as principal components, not original physical measurements. Include the fraction of variance shown and note that the clustering used all four standardized features.
- Compare k=2, 3, and 4 using both a scatterplot and silhouette. Explain a disagreement between visual intuition and a numeric criterion rather than selecting whichever supports a preferred story.
- Repeat the fit on bootstrap samples of training points and predict on the same validation points. Compare partitions with adjusted Rand index. This adds a sample-perturbation check; changing only initialization is a narrower notion of stability.
- Plot the moon data twice, once using generator labels and once using k-means labels. Deliver a short explanation of the geometric mismatch. A passing conclusion does not rename clusters as customer types or claim that a discovered grouping has inherent social meaning.
Common mistakes and repairs
- Treating cluster 0 as smaller or better than cluster 1: cluster labels are arbitrary and can permute between fits.
- Claiming a two-dimensional PCA plot proves separation in original space: projection can hide overlap or distort relationships relevant to the task.
- Maximizing silhouette as if it were a universal truth criterion: it measures a particular distance-based separation and can reward the wrong structure.
Questions that test understanding
Why use adjusted Rand index instead of raw label accuracy?
Two equivalent partitions may name the same groups differently, such as swapping labels 0 and 1. Raw accuracy treats this as complete disagreement. Adjusted Rand index compares pairwise grouping relationships and adjusts for chance, so arbitrary cluster names do not change its meaning.
Does PCA need target labels?
No. PCA learns directions from input variation alone. That makes it useful for compression and exploration, but it does not ensure those directions preserve information about a later target. If used inside supervised selection, fit PCA within each training fold like any other learned transform.
Why might k-means fail on two moons?
Its nearest-center assignment produces convex Voronoi regions in the chosen geometry. Curved interlocking groups are poorly represented by two such regions. The failure is a mismatch between model structure and data geometry, not evidence that the generated curves are meaningless.
Can an extremely stable clustering still be useless?
Yes. A stable partition might separate measurements by instrument calibration, file source, or an arbitrary scale rather than an actionable property. Stability supports repeatability under chosen perturbations; practical value requires external reasoning and an appropriate use case.
Why not cluster the PCA picture automatically?
Reducing to two dimensions discards information and changes distances. It can be a justified modeling choice, but should be evaluated as such. This lesson separates the display transformation from the original standardized clustering so readers do not confuse visualization with the complete data representation.
When is a silhouette score unavailable?
If every point belongs to one group or every point has its own group, the required between- and within-cluster comparison is not defined. A validation subset can also omit some training clusters. Check the number of labels actually predicted before calling the metric.
Exercises with worked solutions
Exercise 1: Test label-permutation invariance
Reveal the worked solution and reasoning
Reassigning names without changing membership preserves adjusted Rand index exactly. This demonstrates why cluster identifiers should not be interpreted numerically or compared directly across independent fits.
Python
renamed = np.array([2, 0, 1])[a]
assert adjusted_rand_score(a, renamed) == 1.0
print("same partition despite different names")
Exercise 2: Inspect a PCA reconstruction
Reveal the worked solution and reasoning
Project standardized validation measurements to two components, then reconstruct them. The mean squared reconstruction error describes discarded variation in standardized units. It does not measure classification accuracy or prove that no important low-variance signal was lost.
Python
restored = pca.inverse_transform(projection)
print("standardized reconstruction MSE", np.mean((Zv - restored) ** 2))
assert restored.shape == Zv.shape
Recap and next step
Unsupervised results require a stated geometry, a reproducible fitting boundary, and evidence beyond a persuasive plot. PCA explains variation; k-means constructs distance-based partitions; stability and silhouette answer limited questions. Next we return to supervised rare events and separate ranking, calibrated probabilities, and cost-sensitive decisions.
Official references
Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.