Sub topic 7
Scaling features before clustering
This chapter assumes you can run Lloyd's algorithm (assign points to the nearest centroid, then move each centroid to the mean of its points). It also assumes you know the Euclidean distance, can read a feature matrix with samples as rows, and have used scikit-learn estimators and pipelines. You should also remember that k-means minimizes inertia, the sum of squared distances from each point to its centroid.
Why k-means is sensitive to units
K-means has no notion of which columns matter. It sees only the Euclidean distance between a row and a centroid:
d(x, c)² = (x₁ − c₁)² + (x₂ − c₂)² + … + (xp − cp)²
Each feature adds its squared difference to the sum. A feature measured in large units produces large differences, so it contributes more to inertia. Changing a column from meters to millimeters multiplies its contribution by one million, even though the information in the column has not changed.
Here is a small example with three customers described by age (years) and annual income (dollars).
| Customer | Age | Income |
|---|---|---|
| A | 30 | 50,000 |
| B | 60 | 51,000 |
| C | 31 | 58,000 |
The distance from A to B is √(30² + 1000²) ≈ 1000.45. The distance from A to C is √(1² + 8000²) ≈ 8000. K-means therefore treats B as much closer to A than C is, although B is 30 years older and C is one year older. Income decides almost everything, and age barely registers.
This is not a bug in the algorithm. It minimizes exactly what you asked it to minimize. The problem is that the raw units were never a sensible definition of "similar".
The effect on the objective
Scaling changes the inertia you are minimizing, so it changes which partitions are good. Consider a feature with a standard deviation of 1000 next to a feature with a standard deviation of 4. Splitting the data along the large feature reduces inertia by an amount proportional to its variance, which is 1,000,000 versus 16. Lloyd's algorithm will prefer the large-variance split almost regardless of where the real group structure lies.
The next script builds this situation on purpose. Feature 0 separates two true groups. Feature 1 is pure noise on a much larger scale. It compares the clusterings against the true groups with the adjusted Rand index, where 1.0 means perfect agreement and values near 0 mean agreement no better than chance.
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 = 200
true_labels = np.repeat([0, 1], n // 2)
# Feature 0: informative. Group centers at 0 and 8, within-group std 1.
f0 = rng.normal(loc=true_labels * 8.0, scale=1.0)
# Feature 1: noise with a large scale (std 1000), unrelated to the groups.
f1 = rng.normal(loc=50_000, scale=1_000, size=n)
X = np.column_stack([f0, f1])
raw = KMeans(n_clusters=2, n_init=10, random_state=0).fit(X)
scaled = make_pipeline(
StandardScaler(),
KMeans(n_clusters=2, n_init=10, random_state=0),
).fit(X)
print("ARI without scaling:", adjusted_rand_score(true_labels, raw.labels_))
print("ARI with scaling: ", adjusted_rand_score(true_labels, scaled[-1].labels_))Without scaling, the ARI is close to zero, because the clusters follow the noise column. With scaling, both columns have unit variance. The informative column now carries a clear two-group structure, and the ARI is close to 1.0.
Common scaling methods
The scaler you choose decides what "equal footing" means. All of these are in sklearn.preprocessing.
| Scaler | Formula | Result | Sensitive to outliers? |
|---|---|---|---|
| `StandardScaler` | (x − mean) / std | Mean 0, std 1 per feature | Yes, mean and std are pulled by extremes |
| `MinMaxScaler` | (x − min) / (max − min) | Range [0, 1] per feature | Very, one extreme value squeezes the rest |
| `RobustScaler` | (x − median) / IQR | Median 0, IQR 1 per feature | Little, median and IQR ignore the tails |
StandardScaler is the usual default for k-means. K-means already uses means and squared distances, and z-scores put every feature's spread on the same scale.
MinMaxScaler is useful when features have natural bounds, or when you want bounded inputs. Its weakness is that a single extreme value fixes the range. If one income is ten times the rest, every other income lands in a narrow band near 0, and the feature effectively loses weight.
RobustScaler keeps outliers from dominating the scale. It does not remove them. An outlier still sits far from everything else after scaling, and k-means can still devote a centroid to it. Scaling is not outlier handling.
Fit the scaler inside a pipeline
Always combine the scaler and the estimator in a Pipeline. This guarantees the same transformation is applied everywhere, and it prevents leakage when you validate on held-out data.
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)
X_train = rng.normal(loc=[0, 500], scale=[1, 100], size=(300, 2))
X_new = rng.normal(loc=[0, 500], scale=[1, 100], size=(5, 2))
model = make_pipeline(
StandardScaler(),
KMeans(n_clusters=3, n_init=10, random_state=1),
)
model.fit(X_train)
# New points are scaled with the training mean and std, then assigned.
print(model.predict(X_new))
# Centroids live in scaled space. Map them back to the original units.
scaler = model[0]
kmeans = model[-1]
centers_original = scaler.inverse_transform(kmeans.cluster_centers_)
print(centers_original)Three details matter here:
predicton new data uses the mean and standard deviation learned from the training data. Never refit the scaler on the new batch, or its points will be placed in a different coordinate system than the centroids.kmeans.cluster_centers_are in scaled units. To describe clusters to other people ("cluster 2 is customers around age 45 with income near $80k"), applyscaler.inverse_transform.kmeans.inertia_is also in scaled units. You can compare inertia between models only if they use the same preprocessing.
Mixed feature types and skew
Real tables mix numeric columns, binary flags, and one-hot encoded categories. A few rules help.
Skewed numeric features. Income, counts, and durations often have a long right tail. After standardization, a few points still sit many standard deviations out, and they drag centroids toward them. A log transform before scaling usually helps. Use np.log1p when zeros are possible.
Binary and one-hot columns. A 0/1 column has a standard deviation of at most 0.5. If you pass it through unchanged, a flip from 0 to 1 adds at most 1 to the squared distance, while a one-standard-deviation change in a standardized column adds 1 as well. Standardizing the binary column instead gives the two values larger gaps when the class is rare. Each choice changes how much the flag counts. There is no neutral choice, so decide deliberately and say which one you made.
Many one-hot columns for one category. A category with 20 levels becomes 20 columns, and two rows with different levels differ in two of them. This gives categorical features a different weight from a numeric feature. K-means is a poor fit for mostly categorical data. Alternatives such as k-modes or k-prototypes are designed for it, and they are outside this chapter.
The following example applies different treatments per column with a ColumnTransformer.
import numpy as np
import pandas as pd
from sklearn.cluster import KMeans
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import FunctionTransformer, StandardScaler
df = pd.DataFrame({
"age": [23, 35, 47, 52, 29, 61, 38, 44],
"income": [28000, 54000, 91000, 120000, 41000, 76000, 450000, 63000],
"is_member": [0, 1, 1, 0, 0, 1, 1, 0],
})
prep = ColumnTransformer([
("age", StandardScaler(), ["age"]),
("income", make_pipeline(FunctionTransformer(np.log1p), StandardScaler()), ["income"]),
("flag", "passthrough", ["is_member"]),
])
model = make_pipeline(prep, KMeans(n_clusters=2, n_init=10, random_state=0))
labels = model.fit_predict(df)
print(labels)Here the income column is log-transformed and then standardized, so the $450,000 value no longer dominates. The membership flag passes through unscaled, which gives it a weight below that of the numeric columns. Change "passthrough" to StandardScaler() and compare the clusters to see how much that one decision matters.
Gotchas
Scaling is not always right. If all features share a physical unit and their relative magnitudes mean something, scaling can destroy information. Examples are pixel intensities in one image, or x and y coordinates on a map. Standardizing a map's coordinates stretches the shorter axis, and clusters that were round in real distance become oval. Check whether your features are comparable before you rescale them.
Scaling sets feature weights. After standardization, every column contributes equally on average. That is a choice, not a fact about your data. If you believe age matters twice as much as income, multiply that scaled column by a weight, for example with a FunctionTransformer or a second ColumnTransformer stage. Treat the weights as hyperparameters and justify them.
Correlated features count twice. If two columns carry nearly the same information, such as height in centimeters and height in inches, scaling gives each one unit variance. Together they contribute double weight. Remove redundant columns or use PCA before clustering. When using PCA, remember that whitening (dividing each component by its standard deviation) puts noise components on the same footing as signal components, which can hurt.
Constant columns. A feature with zero variance cannot be standardized meaningfully. StandardScaler handles it by leaving the scale at 1, so the column becomes all zeros. This is harmless, but it is a sign you can drop the column.
Fitting the scaler on all data, then splitting. If you evaluate clustering stability or silhouette on a held-out set, fit the scaler on the training portion only. Fitting on everything leaks test-set statistics into preprocessing.
Comparing metrics across scalings. Inertia and silhouette are computed in whatever space k-means ran in. An inertia of 120 from standardized data cannot be compared with an inertia of 3.4 million from raw data. When you choose k later, use the same preprocessed matrix for the fit and for the metric. A common bug is calling silhouette_score(X_raw, labels) for labels produced from X_scaled. That measures how well the clusters look in a space k-means never used.
Trying more than one scaler. If results change a lot between StandardScaler and RobustScaler, outliers or skew are probably controlling the clustering. Investigate the data and do not just pick the scaler with the nicer plot.
A short checklist
- Check feature units and ranges with
describe()before you fit anything. - Transform skewed columns (log or power transform) when a long tail is not meaningful.
- Pick a scaler:
StandardScalerby default,RobustScalerwith outliers,MinMaxScalerfor bounded features that have no extreme values. - Decide how to treat binary and one-hot columns, and write it down.
- Put everything in a
Pipelineso the same transform is applied at fit and predict time. - Interpret centroids with
inverse_transform, and compute any evaluation metric in the space the model was fitted in.
Exercise
A dataset has two columns, "distancekm" with values around 0 to 20 and "priceusd" with values around 0 to 2,000,000. You run KMeans on the raw columns and the clusters look like horizontal bands by price. Explain why this happens, and give the pipeline you would use instead, including how you would read the cluster centers in dollars and kilometers.
Show answer
The price column has a far larger variance than the distance column, so squared differences in price dominate the Euclidean distance and inertia. The cheapest way to reduce inertia is to cut along price, which produces bands. Use makepipeline(StandardScaler(), KMeans(nclusters=k, ninit=10, randomstate=0)), or add a log transform for price if it is skewed. Fit the pipeline, then call pipeline[0].inversetransform(pipeline[-1].clustercenters_) to get centers in kilometers and dollars.
Exercise
You fit KMeans on StandardScaler output, then call silhouettescore(Xraw, labels). Why is this a mistake, and what should you pass instead? Separately, why should a new batch of data be scaled with the scaler fitted on the training data?
Show answer
The labels were produced by distances in scaled space, but silhouettescore on Xraw measures separation in raw units, where large-scale features dominate. It reports how well the clusters look in a space k-means never used, so the score is misleading. Pass the scaled matrix X_scaled (or use the pipeline's scaler.transform output). A new batch must use the training mean and standard deviation because the centroids are defined in the training batch's coordinate system. Refitting on the new batch would shift and stretch the points relative to the centroids and give wrong assignments.