Sub topic 6
Why feature scaling matters
This chapter assumes you know how k-NN classifies with Euclidean distance, and that you can use scikit-learn estimators and train_test_split.
Distance treats every unit the same
k-NN ranks neighbours by a distance computed over all features at once. The distance does not know that one feature is measured in years and another in dollars. It adds up squared differences, so a feature with a large numeric range dominates the sum.
Take two features, age in years and income in dollars. Compare a query person (age 26, income 52,000) with two stored people:
| Person | Age | Income | Age gap to query | Income gap to query | Euclidean distance |
|---|---|---|---|---|---|
| A | 25 | 50,000 | 1 | 2,000 | about 2000.0 |
| B | 60 | 51,000 | 34 | 1,000 | about 1000.6 |
Person B is 34 years older, yet B is the nearer neighbour. The age gap contributes 34² = 1,156 to the squared distance. The income gap contributes 1,000,000. Age is effectively ignored, and the model behaves as if it had only one feature.
Two common fixes
Scaling rewrites each feature so that gaps are comparable across features.
- Standardisation subtracts the feature mean and divides by its standard deviation, giving mean 0 and variance 1. In scikit-learn this is
StandardScaler. - Min-max scaling maps each feature to a fixed range, usually 0 to 1, using
(x - min) / (max - min). In scikit-learn this isMinMaxScaler.
Standardisation is a sensible default. Min-max scaling is easy to interpret, but one extreme outlier stretches the range and squeezes all other values into a narrow band. If outliers are heavy, consider RobustScaler, which uses the median and interquartile range.
Scale inside a pipeline
The scaler learns its statistics (means and standard deviations) from data. If you fit it on the whole dataset before splitting, information from the test rows leaks into training. This is data leakage, and it makes your score look better than it will be in practice.
The fix is to put the scaler and the classifier in one Pipeline. Calling fit on the pipeline fits the scaler on the training data only. It then applies the same transformation to any new data. Inside cross-validation, this happens separately for each fold.
Measuring the effect
This script trains the same classifier on the wine dataset twice, once on raw features and once with scaling. The wine features have very different ranges. For example, proline is in the hundreds or thousands, while hue is near 1.
from sklearn.datasets import load_wine
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_wine(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=0
)
raw = KNeighborsClassifier(n_neighbors=5).fit(X_train, y_train)
scaled = make_pipeline(
StandardScaler(), KNeighborsClassifier(n_neighbors=5)
).fit(X_train, y_train)
print("raw: ", raw.score(X_test, y_test))
print("scaled:", scaled.score(X_test, y_test))Run it and compare the two accuracies. On this dataset the scaled model is typically clearly better, because proline no longer swamps the other twelve features.
Common errors
- Fitting the scaler on all data. Always scale through a pipeline, as above, rather than calling
fit_transformon the full dataset. - Scaling train and test separately. Calling
fit_transformon the test set computes new statistics from it. The test set must use the training statistics throughtransform. - Scaling one-hot columns blindly. Binary columns are already on a 0 to 1 scale. Standardising them changes their weight in the distance. Decide deliberately how much influence each group of features should have.
- Assuming scaling is always needed. If all features share the same unit and a similar range, such as pixel intensities, scaling may not matter. Check with cross-validation instead of guessing.
Scaling also gives you a lever. Multiplying a scaled feature by a weight greater than 1 makes it count more in the distance. That is a form of feature weighting, and you can tune it, but start with equal scales.
Exercise
A k-NN model uses two features: height in metres (range about 1.5 to 2.0) and weight in grams (range about 50,000 to 120,000). Which feature dominates the distance, and what should you do so that the model is evaluated fairly in 5-fold cross-validation?
Show answer
Weight in grams dominates, because its differences are tens of thousands of times larger than the height differences. Build a pipeline such as makepipeline(StandardScaler(), KNeighborsClassifier()) and pass the pipeline to crossval_score or GridSearchCV with cv=5. The scaler is then refit on the training folds of each split, so the validation fold never influences the scaling statistics.