Intermediate: machine learning · Clustering, dimensionality reduction and feature engineering · topic 41 of 62 · 30 min
Scaling and transforming numbers
Explanation
Why scale?
Features come in very different units: age (18–80), monthly income (₹10,000–₹10,00,000), number of past loans (0–10). k-NN, k-means, SVMs, PCA and anything trained by gradient descent are affected by these sizes. Income would dominate distances and slow down gradient descent. Scaling removes the unfair advantage of big numbers.
Min-max scaling
x_scaled = (x − min) ÷ (max − min). The smallest training value becomes 0 and the largest becomes 1. It keeps the shape of the data, but one extreme outlier squashes everything else into a tiny range. New values outside the training range will fall below 0 or above 1, which is fine.
Standardisation (z-scores)
x_scaled = (x − mean) ÷ standard deviation. The result has mean 0 and standard deviation 1, like the z-scores from module 2. It is the most common choice and is less squeezed by single outliers than min-max. RobustScaler goes further, using the median and IQR, which are barely moved by outliers.
values = [10, 20, 30, 40]
mn, mx = min(values), max(values)
print([(v - mn) / (mx - mn) for v in values])
import statistics
m, sd = statistics.mean(values), statistics.pstdev(values)
print([round((v - m) / sd, 4) for v in values])Fit on train, apply to test
The min, max, mean and standard deviation are learned values, just like model weights. Learn them from the training data only, then use the same numbers to transform validation, test and future data. If you compute them from all the data, information from the test set leaks into training. In scikit-learn: scaler.fit(X_train), then scaler.transform(X_test); a Pipeline does this automatically.
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler().fit(X_train)
X_train_s = scaler.transform(X_train)
X_test_s = scaler.transform(X_test) # same mean and std as trainingLog and other transforms
Incomes, house prices and city populations are right-skewed: most values are small and a few are huge. Taking the logarithm, log(1 + x) to handle zeros, pulls in the long tail and often makes relationships more linear. If you transform the target, remember to transform predictions back (for example with exp) before reporting them.
Scaling inside cross-validation
The same rule applies inside cross-validation: in every fold, the scaler must be fitted on the training part of that fold only. Doing this by hand is easy to get wrong, which is why the scaler is normally placed inside a scikit-learn Pipeline together with the model (topic 5). The pipeline is then passed to cross_val_score or GridSearchCV, and it refits the scaler correctly in each fold without any extra code from you.
Which models need scaling?
| Needs scaling | Does not need scaling |
|---|---|
| k-NN, k-means, SVM, PCA | Decision trees |
| Linear/logistic regression with regularisation | Random forests |
| Neural networks | Gradient boosted trees |
Common mistakes
- Fitting the scaler on all data before splitting (leakage).
- Scaling the target for a regression model and forgetting to unscale the predictions.
- Dividing by a zero standard deviation for a constant column. Fix: drop constant columns or guard the division.
- Scaling one-hot columns unnecessarily; it is usually harmless but adds confusion.
Need help?
Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.
Try:
Watch the lesson
Scaling and transforming numbers · 1/6
Features come in very different units. Scaling puts them on a fair footing.
Prefer a video by a teacher? Find free videos on “feature scaling standardization normalization min max machine learning” on YouTube ↗
In real life: Scaling for a credit-risk k-NN prototype
An analyst prototyping a "similar past applicants" tool with k-NN first found that every neighbour simply had a similar income, because income in rupees dwarfed all other features. After standardising every feature using means and standard deviations from the training applicants only, the neighbours matched on repayment history and loan size too, and the tool's suggestions finally made sense to credit officers.
Practice (0/2 done)
Write minmax_scale(values) that returns (v − min) / (max − min) for each value, rounded to 4 decimal places. If all values are equal, return a list of 0.0. Return [] for an empty list.
Write fit_standardizer(train) that returns (mean, sd) of the training values using statistics.mean and statistics.pstdev, and transform(values, mean, sd) that returns (v − mean) / sd rounded to 4 decimal places (all 0.0 if sd is 0). This is how you scale test data with numbers learned from training data.
Quick quiz
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Feature selection, leakage and pipelinesClustering, dimensionality reduction and feature engineering · same module
- Other clustering methods and dimensionality reductionClustering, dimensionality reduction and feature engineering · same module
- Cross-validation and tuning hyperparametersEvaluating models
- Train, validation and test setsEvaluating models
- The normal distribution and z-scoresStatistics made simple
- Load balancing and auto scalingCloud Computing (AWS, Azure, Google Cloud) · High availability, scaling and disaster recovery
Questions people ask about this
Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.
After standardisation, a feature has…
Answer: Mean 0 and standard deviation 1
That is the definition of standardisation.
Which model does NOT need feature scaling?
Answer: Random forest
Trees split one feature at a time on thresholds.
Where should the scaler learn its mean and standard deviation?
Answer: From the training data only
Anything else leaks test information.
Incomes are very right-skewed. Which transform often helps?
Answer: log(1 + x)
A log pulls in the long tail.
Min-max scaling with one huge outlier will…
Answer: Squash most other values into a tiny range near 0
The outlier sets the max, so the rest crowd together.
Features are salary in rupees and age in years, unscaled. What goes wrong in k-NN?Related
Answer: Distance is dominated by salary, so age is almost ignored
Large-valued features swamp the distance. Scale first.
From k-nearest neighbours
Delivery times have a variance of 49 square minutes. What is the standard deviation?Related
Answer: 7 minutes
The SD is the square root of the variance: √49 = 7, back in minutes.
In 5-fold cross-validation, how many times is the model trained?Related
You scale features using the mean and standard deviation of the WHOLE dataset before splitting. What is the problem?Related
Answer: Test-set information leaks into training
Fit preprocessing on the training set only, then apply it to the test set.
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.
Next steps
- 1 more topic in “Clustering, dimensionality reduction and feature engineering” before its exam: Feature selection, leakage and pipelines.
- Module 8 exam: Clustering, dimensionality reduction and feature engineering · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
- Then the next module, Neural networks and deep learning. 62 topics left in the course before the final exam.