Sub topic 7
Scaling Features Before Clustering
This chapter assumes you can use NumPy arrays, know that k-means assigns each point to its nearest centroid by Euclidean distance, and treat a dataset as a matrix with samples in rows and features in columns. You should also know what inertia is, since we use it to check results.
Why distance depends on units
K-means decides cluster membership using Euclidean distance. That distance adds up squared differences across all features. If one feature has a much larger numeric range than the others, its differences dominate the sum, and the other features barely affect which centroid is nearest.
Suppose each customer has an age (about 20 to 70) and an annual income in dollars (about 20,000 to 150,000). A 10-year age gap is a large difference between people. A $10 income gap is trivial. Yet in raw units the income gap contributes 100 to the squared distance, and the age gap contributes the same 100. The two look equal. A $5,000 income gap, which is small, contributes 25,000,000, and it swamps the age gap completely.
The algorithm has no idea that age is measured in years and income in dollars. It sees only numbers. Changing the unit of a feature (dollars to thousands of dollars) changes the clusters you get. A result that depends on the unit you happened to pick is rarely what you want.
Standardization
The most common fix is standardization, also called z-scoring. For each feature column, subtract that column's mean and divide by its standard deviation:
z = (x − mean) / std
After this, every feature has mean 0 and standard deviation 1. A value of 1.0 means "one standard deviation above average" whatever the original unit was.
Other scalers exist.
| Scaler | Formula idea | Use when |
|---|---|---|
| `StandardScaler` | subtract mean, divide by std | Default choice; features are roughly bell-shaped |
| `MinMaxScaler` | map to the range 0 to 1 | You need a bounded range; no strong outliers |
| `RobustScaler` | subtract median, divide by interquartile range | Outliers are present |
Min-max scaling is sensitive to outliers. One extreme value stretches the range and squeezes all other points into a narrow band.
Seeing the effect
The example below builds two features with very different scales. The first column carries the real cluster structure at a small scale. The second column is mostly noise, but at a much larger scale. We compare the labels k-means finds with and without scaling against the true groups using the adjusted Rand index, where 1.0 means a perfect match.
import numpy as np
from sklearn.cluster import KMeans
from sklearn.metrics import adjusted_rand_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
rng = np.random.default_rng(0)
n = 300
true = np.repeat([0, 1, 2], n // 3)
# Feature 1: clear cluster structure, small scale
f1 = rng.normal(loc=true * 4.0, scale=1.0)
# Feature 2: uninformative noise, large scale
f2 = rng.normal(loc=0.0, scale=1000.0, size=n)
X = np.column_stack([f1, f2])
raw = KMeans(n_clusters=3, n_init=10, random_state=0).fit_predict(X)
scaled = make_pipeline(
StandardScaler(),
KMeans(n_clusters=3, n_init=10, random_state=0),
).fit_predict(X)
print("raw ARI:", round(adjusted_rand_score(true, raw), 3))
print("scaled ARI:", round(adjusted_rand_score(true, scaled), 3))On the raw data the noise column controls the distances, so the clusters have little to do with the true groups and the score is near 0. After scaling, the noise column has the same weight as the informative one. The score rises, but it will not be perfect, because the noise feature still adds some variation.
Scaling is not a cure for irrelevant features. It makes features comparable, and it does not decide which features matter. If a feature carries no structure, remove it.
Common errors
- Scaling the output only. Fit the scaler on the training data and keep it. If you later assign new points to clusters, call
transformwith the same fitted scaler. Fitting a new scaler on the new data shifts the coordinate system. - Reading centroids in the wrong units. After scaling,
cluster_centers_is in scaled space. To report centroids in original units, usescaler.inverse_transform. - Scaling one-hot columns blindly. Standardizing a 0/1 indicator column makes it behave differently from how you intended. Decide deliberately whether such columns should have the same influence as continuous ones.
- Always scaling out of habit. If all features share the same unit and the differences in range are meaningful, such as pixel intensities or coordinates in meters, scaling may remove real information. Check whether equal weighting is what you want.
Recovering centroids in original units
import numpy as np
from sklearn.cluster import KMeans
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
rng = np.random.default_rng(1)
age = rng.normal([25, 45, 65], 4, size=(100, 3)).T.ravel()
income = rng.normal([30000, 70000, 110000], 5000, size=(100, 3)).T.ravel()
X = np.column_stack([age, income])
model = make_pipeline(StandardScaler(), KMeans(n_clusters=3, n_init=10, random_state=1))
model.fit(X)
scaler, km = model[0], model[-1]
centers = scaler.inverse_transform(km.cluster_centers_)
print(np.round(centers[np.argsort(centers[:, 0])]))The printed rows are cluster centers as (age, income), sorted by age, and they should land near the three group means you generated.
Exercise
A dataset has two features: height in meters (range 1.5 to 2.0) and weight in grams (range 50,000 to 120,000). You run k-means without scaling. Which feature controls the clusters, and why? Name one fix and one situation where you would not apply it.
Show answer
Weight controls the clusters. Its differences are thousands of times larger than height differences, so they dominate the squared Euclidean distance. Fix: standardize both features with StandardScaler before fitting. You would skip scaling when the features share a unit and their relative ranges are meaningful, for example x and y coordinates measured in the same unit, where scaling would distort real distances.