Sub topic 3
Scaling features before clustering
Hierarchical clustering and DBSCAN both group points by distance. If one feature has a much larger numeric range than the others, it controls the distance and the other features barely count. This chapter shows how that happens, which scalers fix it, and where scaling can hurt.
This chapter assumes you know Euclidean distance, basic NumPy, and scikit-learn's fit and transform pattern. The previous chapter covered distance measures.
Why distance-based methods need scaling
Euclidean distance adds the squared difference of every feature. Take two people described by age in years and yearly income in dollars:
- Person A: age 25, income 50,000
- Person B: age 60, income 51,000
The age gap is 35 and the income gap is 1,000. The distance is about 1,000.6, and almost all of it comes from income. Clustering would treat the 35-year age gap as negligible. If you recorded income in thousands of dollars, the income gap would be 1 and age would dominate instead. The clusters would change only because you changed the unit.
Every method in this tutorial is affected:
- Single, complete, and average linkage compare raw pairwise distances.
- Ward linkage minimizes the increase in within-cluster variance. Features with large variance dominate that sum.
- DBSCAN uses one
epsradius for all features. A single radius only makes sense if one unit of distance means roughly the same thing on every axis.
Tree-based models do not have this problem, because they split on one feature at a time. Distance-based clustering does.
A demonstration
The next example builds two true groups that differ only on a small-scale feature. A second feature is pure noise with a huge range. We cluster once on raw data and once on scaled data, then compare each result with the true groups using the adjusted Rand index (ARI). An ARI near 1 means the clustering matches the groups. An ARI near 0 means it is no better than random.
import numpy as np
from sklearn.cluster import AgglomerativeClustering
from sklearn.datasets import make_blobs
from sklearn.metrics import adjusted_rand_score
from sklearn.preprocessing import StandardScaler
# Feature 0 separates two groups. Feature 1 is noise with a range near 1000.
signal, y_true = make_blobs(
n_samples=200, centers=[[0.0], [6.0]], cluster_std=1.0, random_state=0
)
rng = np.random.default_rng(0)
noise = rng.normal(0, 1000, size=(200, 1))
X = np.hstack([signal, noise])
model = AgglomerativeClustering(n_clusters=2, linkage="ward")
raw_labels = model.fit_predict(X)
scaled_labels = model.fit_predict(StandardScaler().fit_transform(X))
print("raw ARI:", round(adjusted_rand_score(y_true, raw_labels), 2))
print("scaled ARI:", round(adjusted_rand_score(y_true, scaled_labels), 2))On raw data the noise feature is about a thousand times larger than the signal, so the split follows the noise and the ARI is near 0. After StandardScaler the signal feature carries most of the variance, because it is bimodal. Ward then splits on it and the ARI is close to 1. Exact values depend on your library version.
Choosing a scaler
scikit-learn provides three common scalers. Each is fit on the data to learn its statistics, then applied with transform.
| Scaler | Formula | Result | Sensitive to outliers? |
|---|---|---|---|
| `StandardScaler` | (x − mean) / std | Mean 0, standard deviation 1 | Yes. Mean and std are pulled by extremes. |
| `MinMaxScaler` | (x − min) / (max − min) | Range [0, 1] | Very. One extreme sets the whole range. |
| `RobustScaler` | (x − median) / IQR | Median 0, IQR 1 | Much less. Uses the median and interquartile range. |
StandardScaler is the usual default. Outliers are the main reason to choose something else. The next example shows the effect on one feature with a single extreme value:
import numpy as np
from sklearn.preprocessing import RobustScaler, StandardScaler
x = np.array([[1.0], [2.0], [3.0], [4.0], [5.0], [1000.0]])
print(StandardScaler().fit_transform(x).ravel().round(3))
print(RobustScaler().fit_transform(x).ravel().round(3))The standard-scaled values of the five ordinary points are all close to -0.45, squeezed into a range of about 0.01. The outlier inflated the standard deviation, so the ordinary points became almost indistinguishable. RobustScaler returns -1.0, -0.6, -0.2, 0.2, and 0.6 for them, and the outlier stays far away at about 198.6.
Scaling and the clustering parameters
The meaning of eps changes
DBSCAN's eps is measured in the units of the data you pass in. After StandardScaler, eps=0.3 means "within 0.3 standard deviations" across the features combined. A value tuned on raw data will not transfer to scaled data, and the reverse is also true. Always choose eps after you fix the scaling step. The k-distance plot later in this tutorial should also be computed on the scaled data.
Ward and variance
Ward linkage is defined through variance, so scaling directly changes what it minimizes. The same holds for KMeans. When features are on very different scales, Ward is effectively clustering on the largest one.
Keep scaling and clustering together
A Pipeline keeps the two steps tied together, so you cannot tune one and forget the other:
from sklearn.cluster import DBSCAN
from sklearn.datasets import make_moons
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, _ = make_moons(n_samples=300, noise=0.05, random_state=0)
pipe = make_pipeline(StandardScaler(), DBSCAN(eps=0.3, min_samples=5))
labels = pipe.fit_predict(X)
print(sorted(set(labels)))Pipeline.fit_predict is available because the last step has fit_predict. If you later need to place new points relative to an existing clustering, reuse the fitted scaler with scaler.transform(new_X). Do not call fit_transform on the new data, or its statistics will differ from those used for the original clustering. DBSCAN and AgglomerativeClustering have no predict, so you would then need your own rule, such as nearest core point.
Common errors and judgment calls
- Scaling when units already match. If all features share one unit and scale, such as pixel intensities or coordinates in meters, scaling can destroy meaningful differences. A feature with real, large spread may deserve a large weight.
- Scaling away a feature's importance. Standardizing gives every feature equal variance. A noise feature then gets as much influence as a useful one. Drop irrelevant features first.
- Binary and one-hot columns. A 0/1 column has a standard deviation that depends on how often the 1 appears. After standardization, rare categories get large values. Consider whether Euclidean distance suits mixed data at all. Gower distance or a different method may fit better.
- Skewed features. Income-like data with a long tail stays skewed after standardization. A log transform before scaling often helps more than switching scalers.
- Deliberate weighting. After scaling, you can multiply a column by a factor above 1 to make it count more. This is a legitimate way to encode domain knowledge, but record the factor.
- Comparing runs. Silhouette scores computed on scaled and unscaled data are not comparable, because the distances differ. Compare clusterings on one fixed representation.
Exercise
You tune DBSCAN with eps=0.5 on StandardScaler output and get good clusters. A colleague reruns it on the raw data with the same eps and gets one cluster plus a lot of noise points, or one giant cluster. Why does eps=0.5 behave so differently, and what should they do?
Show answer
eps is measured in the units of the input data. On raw data a feature with a range of thousands makes most pairwise distances far larger than 0.5, so very few points have enough neighbors and most are labeled noise. If the raw ranges are small, the radius can instead cover everything and merge it into one cluster. The colleague should apply the same fitted scaling step, for example with a Pipeline, and then use eps=0.5, or retune eps with a k-distance plot on whatever representation they choose.
Exercise
A dataset has one feature with a few extreme outliers. You apply MinMaxScaler and then Ward clustering, and nearly all points end up in one tight clump on that feature. Which scaler would you try instead, and why?
Show answer
Try RobustScaler. MinMaxScaler maps the single minimum and maximum to 0 and 1, so one extreme value stretches the range and compresses all the ordinary points into a tiny interval. RobustScaler uses the median and interquartile range, which the outliers barely affect, so the ordinary points keep a useful spread.