Sub topic 6
Why feature scaling matters
This chapter assumes you know how k-NN classifies by majority vote and how Euclidean and Manhattan distances are computed. It also assumes you can read a scikit-learn pipeline and a train/test split. The goal is to show why raw feature values can break k-NN, how to fix that, and how to avoid the leakage mistakes that often come with the fix.
The problem: distance treats every unit equally
k-NN has no learned parameters. The only thing that decides which points are neighbours is the distance function. Euclidean distance adds up squared differences across features, so a feature measured in thousands contributes far more than one measured in single digits. The metric does not know that "30 years" and "30 dollars" mean different things. It sees only the number 30.
Consider three people described by age (years) and income (dollars):
import numpy as np
query = np.array([30, 50000]) # age 30, income 50,000
b = np.array([60, 50100]) # 30 years older, income 100 higher
c = np.array([31, 52000]) # 1 year older, income 2,000 higher
print(np.linalg.norm(query - b)) # about 104.4
print(np.linalg.norm(query - c)) # about 2000.0
# Rescale each feature by a typical spread: 10 years, 10,000 dollars
scale = np.array([10, 10000])
print(np.linalg.norm((query - b) / scale)) # about 3.0
print(np.linalg.norm((query - c) / scale)) # about 0.22With raw values, b is the nearest neighbour, even though that person is 30 years older. The income difference of 2,000 dwarfs the age difference. After dividing each feature by a typical spread, c is nearest, which matches most people's idea of "similar". The same data gives opposite neighbours depending on units.
The effect is not limited to Euclidean distance. Manhattan and Minkowski distances also sum per-feature differences, so they have the same problem. Changing the metric does not remove the need to scale.
Common scaling methods
The usual approach is to transform each feature so its values sit on a comparable scale. Each method below computes its parameters per feature (per column).
| Method | Formula | Result | Sensitive to outliers? |
|---|---|---|---|
| Standardisation (`StandardScaler`) | (x − mean) / std | Mean 0, standard deviation 1 | Yes, mean and std are pulled by extremes |
| Min-max scaling (`MinMaxScaler`) | (x − min) / (max − min) | Values in [0, 1] on training data | Strongly, one outlier compresses everything else |
| Robust scaling (`RobustScaler`) | (x − median) / IQR | Median 0, interquartile range 1 | Little |
Standardisation is the usual default for k-NN. Min-max scaling is common when you want bounded features, for example pixel intensities. Robust scaling helps when a few extreme values would otherwise squash the bulk of the data into a narrow band.
Some details matter in practice:
- Outliers distort scaling. With min-max scaling, a single value 100 times larger than the rest maps typical points into a tiny interval near 0. Their differences then barely count in the distance.
- Skewed features such as income or counts may need a log transform before scaling. Scaling fixes the spread but not the shape.
- Constant columns have zero variance.
StandardScalerleaves them at 0 and does not divide by zero, but the column carries no information and can be dropped. - Test data can fall outside [0, 1] after min-max scaling, because the scaler uses the training minimum and maximum. This is expected and not an error.
Seeing the effect on real data
The wine dataset has 13 numeric features. Proline values run into the hundreds and thousands, while others such as hue stay near 1. Unscaled, proline almost decides the distance by itself. The comparison below uses cross-validation on both versions.
from sklearn.datasets import load_wine
from sklearn.model_selection import cross_val_score
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_wine(return_X_y=True)
raw = KNeighborsClassifier(n_neighbors=5)
scaled = make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=5))
print("raw :", cross_val_score(raw, X, y, cv=5).mean())
print("scaled:", cross_val_score(scaled, X, y, cv=5).mean())Run it yourself. The scaled pipeline should score clearly higher, often by more than 20 percentage points. The exact numbers depend on your scikit-learn version and the fold splits. The size of the gap is the point: scaling can matter more than any choice of k.
Where to fit the scaler: avoid leakage
The scaler learns its parameters (mean and standard deviation, or min and max) from data. Those parameters must come from the training data only. If you fit the scaler on the full dataset before splitting, information about the test rows leaks into training. Test points then help define the scale, and your score becomes slightly optimistic.
The leaky version looks harmless:
from sklearn.datasets import load_wine
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.preprocessing import StandardScaler
X, y = load_wine(return_X_y=True)
# Wrong: the scaler sees every row, including future test rows
X_leaky = StandardScaler().fit_transform(X)The correct manual version fits on the training split and only applies the result to the test split:
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=0
)
scaler = StandardScaler().fit(X_train) # learn mean/std from train only
X_train_s = scaler.transform(X_train)
X_test_s = scaler.transform(X_test) # reuse the same mean/std
knn = KNeighborsClassifier(n_neighbors=5).fit(X_train_s, y_train)
print(knn.score(X_test_s, y_test))The best solution is a Pipeline. When you cross-validate a pipeline, scikit-learn refits the scaler inside each training fold and applies it to the matching validation fold. You cannot forget a step, and the same transformation is applied at prediction time automatically.
Scaling is also a way to weight features
Standardising gives every feature equal say in the distance. That is a modelling choice, not a neutral default. If you know a feature is more informative, you can multiply its scaled column by a weight greater than 1 to make it count more in the distance. Multiplying by a weight below 1 does the opposite. Automatic ways to learn such weights exist, but even a manual choice shows that "scale" and "importance" are tied together in k-NN.
This also explains an issue with irrelevant features. Standardisation boosts a noisy column up to the same scale as useful ones, so a feature that carries no signal now adds random distance. Scaling does not remove the need for feature selection. The chapter on the curse of dimensionality returns to this.
Special cases
Binary and one-hot features
A one-hot column takes values 0 or 1. Standardising it can make rare categories jump to large values. For a column where only 2% of rows are 1, the 1 becomes about 7 standard deviations from the mean. That makes the rare category dominate distances. Often it is better to leave one-hot columns unscaled, or to scale them separately, and to treat the choice as something you tune. Scaling only some columns is done with ColumnTransformer.
Sparse data
Subtracting the mean makes a sparse matrix dense and can exhaust memory. Use StandardScaler(with_mean=False) or MaxAbsScaler, both of which preserve sparsity.
Cosine distance
If you use cosine distance, only the direction of each vector matters, not its length. Scaling each row to unit length (Normalizer) is the matching preprocessing step. This is row-wise normalisation. It is different from column-wise feature scaling, so do not mix them up.
Features already on one scale
If all features are the same kind of quantity in the same unit, for example pixel intensities from 0 to 255, scaling may not be needed. Rescaling can still help numerically, but it will not change which neighbours are chosen if every column gets the same linear factor.
Checklist
- Look at the range and spread of each feature before choosing a scaler.
- Choose a scaler that suits outliers and skew in the data.
- Put the scaler and the k-NN estimator in one
Pipeline. - Tune
n_neighborsandweightson the pipeline, not on pre-scaled data. - For mixed data, scale numeric columns and treat categorical columns on their own.
Exercise
A k-NN model uses height in centimetres (typical range 150 to 200) and annual salary in dollars (typical range 20,000 to 200,000). A colleague says that after min-max scaling both features, the model is ready, but one salary of 5,000,000 is in the training data. What problem remains, and what would you change?
Show answer
The outlier sets the maximum, so after min-max scaling almost all real salaries fall into a tiny interval near 0 (about 0 to 0.04). Salary differences between ordinary people then barely affect the distance, and height dominates. Use a scaler less sensitive to extremes, such as RobustScaler, or clip or log-transform salary first. Fit the scaler inside a pipeline so the training data alone defines the scale.
Exercise
You scale the whole dataset with StandardScaler, split it into train and test sets, and report a test accuracy of 0.96. Why might this overstate real performance, and how do you fix it?
Show answer
The scaler's mean and standard deviation were computed using the test rows, so test information leaked into preprocessing. The effect is usually small but it breaks the separation between training and test data. Split first, then fit the scaler on the training set only and apply transform to the test set. Better, wrap the scaler and KNeighborsClassifier in make_pipeline so cross-validation refits the scaler within each fold.