Feature Scaling — Standardisation and Normalisation
Why scale matters, what StandardScaler and MinMaxScaler actually do under the hood, which algorithms break without scaling, and when to use each scaler.
Your model thinks $500 and 5km are the same magnitude. They are not.
A DoorDash delivery prediction model has two features: distance in kilometres (range 0.5–15) and order value in dollars (range 50–1200). To gradient descent, $1200 looks 80 times more important than 15km simply because the number is bigger — not because it actually is. The optimiser takes tiny steps in the distance direction and massive steps in the order-value direction, oscillating and converging slowly or not at all.
This is the scaling problem. It is not a subtle edge case. For gradient-based algorithms (linear regression, logistic regression, SVMs, neural networks, K-means) unscaled features produce models that are slower to train, less accurate, and sensitive to which units you happened to measure in. A model trained on distances in kilometres gives different results than one trained on the same distances in metres — even though the data contains identical information.
Feature scaling solves this by transforming all features to a common scale before training. This module shows you exactly what each scaler does mathematically, which algorithms need it, and how to apply it correctly inside a sklearn Pipeline without leaking test information.
What this module covers:
What unscaled features do to gradient descent
Imagine the loss surface as a landscape with hills and valleys. With well-scaled features the loss surface looks like a round bowl — gradient descent rolls straight down to the minimum from any starting point. With badly scaled features the surface becomes an elongated narrow valley — gradient descent bounces left and right off the steep walls while crawling slowly toward the minimum. The same distance to the minimum, but zigzagging makes the journey 10× or 100× longer.
StandardScaler — zero mean, unit variance
StandardScaler transforms each feature so it has mean 0 and standard deviation 1. Every value is expressed as "how many standard deviations from the mean is this?" A distance of 6km in a dataset with mean 4km and std 2km becomes (6 − 4) / 2 = 1.0 — one standard deviation above average. A distance of 2km becomes −1.0.
When StandardScaler is the right choice
StandardScaler preserves the Gaussian shape — scaled values are still normally distributed, just centred at 0 with std 1.
Linear/logistic regression, SVMs, neural networks, K-means, PCA — all assume features are on comparable scales.
Unlike RobustScaler, StandardScaler is affected by outliers. Use this when extreme values carry meaningful signal.
MinMaxScaler — compress every feature to [0, 1]
MinMaxScaler shifts and scales each feature so the minimum becomes 0 and the maximum becomes 1. All values end up strictly between 0 and 1. The shape of the distribution is preserved — the relative distances between values stay the same, just rescaled to fit the [0, 1] window.
RobustScaler — scale using median and IQR, not mean and std
StandardScaler uses the mean and standard deviation. Both are sensitive to outliers — one extreme value can shift the mean dramatically and inflate the standard deviation, causing all other values to be squashed into a tiny range after scaling. RobustScaler uses the median (Q2) and interquartile range (IQR = Q3 − Q1) instead. These are resistant to outliers by construction: no matter how extreme one value is, the median and IQR barely change.
MaxAbsScaler and Normalizer — the two special-purpose scalers
Two more scalers cover specific situations that StandardScaler, MinMaxScaler, and RobustScaler don't handle well.
MaxAbsScaler — for sparse data
MaxAbsScaler divides each feature by its maximum absolute value, producing values in [−1, 1]. Crucially, it does not centre the data (no mean subtraction). This preserves sparsity — if a feature was 0, it stays 0. StandardScaler would subtract the mean and create non-zero values where there were zeros, destroying the sparsity that makes sparse matrix operations fast. Use MaxAbsScaler for TF-IDF vectors, one-hot encoded matrices, and any sparse input.
Normalizer — scale rows, not columns
Every scaler so far operates on columns — each feature is scaled independently. Normalizer is different: it scales each sample (row) so its length equals 1. This is used when the direction of a feature vector matters more than its magnitude — text classification with TF-IDF, recommendation systems, cosine similarity computations.
Which algorithms need scaling — and which genuinely don't
Not every algorithm is sensitive to feature scale. Tree-based models split on threshold values — the scale of a feature does not change whether splitting at 3.5km vs 4.2km produces purer leaf nodes. But every algorithm that computes distances, dot products, or gradients is directly affected by scale. Knowing which is which prevents wasted preprocessing and wrong assumptions.
Scalers inside a Pipeline — the only safe way
The most common scaling mistake is fitting the scaler on the entire dataset before the train/test split. This leaks test statistics — the test set's mean and standard deviation influence the scaler, which in turn influences what the model sees during training. Evaluation metrics look slightly better than they should, and the model is technically trained on information from the test set.
A sklearn Pipeline completely prevents this. It fits the scaler only when pipe.fit(X_train) is called, and applies the stored statistics (never refitting) when pipe.predict(X_test) is called. There is no way to accidentally leak using a Pipeline.
Should you scale the target variable?
You almost never need to scale y for linear regression or tree models. The model adjusts its bias term to match the scale of y automatically. But for neural networks — especially deep ones — a target with a large range (like delivery times 10–120 minutes) can cause unstable training because the output layer needs large weights to produce large numbers. Scaling y to zero mean and unit variance stabilises training.
Which scaler to use — decision guide
Every common scaling error — explained and fixed
Scaling in a real pipeline — not a one-off fit_transform in a notebook
In a notebook, scaling is one line: fit_transform, done. In production it is a versioned artifact that has to travel with the model and be reproduced exactly, every single time, for every single request. A fitted StandardScaler stores a mean and a standard deviation for each feature — those numbers are frozen the moment training ends, and every prediction the model ever makes, in batch or in real time, has to be scaled using those exact frozen numbers, not numbers recomputed from whatever data happens to be around at the time.
The distance-based-versus-tree-based distinction from this module shows up constantly in how teams design a pipeline. A team that only ever ships gradient boosted trees can often skip scaling entirely and simplify their feature pipeline. A team that swaps between linear models, SVMs, and trees during experimentation usually scales everything by default anyway — it costs almost nothing for a tree model to receive scaled input, but it is a correctness requirement for the others, so standardising the pipeline avoids a class of "why did the model get worse when we swapped algorithms" bugs.
The single most common production bug involving scaling is not a math mistake — it is train/serve skew: the offline training pipeline and the online serving path compute the "same" feature slightly differently. A distance feature computed in kilometres during offline training but delivered in miles by a real-time feature store will silently feed the scaler numbers it never expected — the model still returns a confident prediction, it is just quietly wrong, and nothing crashes to tell anyone.
This is also why scaler statistics get monitored the same way model predictions do. Teams track the distribution of each incoming feature against the distribution the scaler was fit on — if the live mean for order value drifts far from the training-time mean, that is an early warning that either the business has changed (prices went up) or a feature is broken upstream, and either way the model likely needs retraining before its accuracy visibly degrades.
Five things people get wrong about feature scaling
Scaling is a fix for a specific failure mode: algorithms whose math directly depends on the numeric magnitude of a feature, through a distance calculation, a dot product, or a gradient step. Tree-based models split on a threshold value one feature at a time — whether that threshold sits at 3.5 or 3,500 does not change which side of the split a row falls on, so scaling a feature before feeding it to a random forest or XGBoost changes nothing about the model it learns. Scaling everything by habit is harmless, but treating it as a universal requirement misses why it works, which matters the moment someone asks you to justify skipping it for a tree-based pipeline.
They make different assumptions and produce genuinely different distributions. StandardScaler centres data at zero with unit variance and preserves a roughly Gaussian shape, but the output is unbounded — an outlier still produces a very large scaled value. MinMaxScaler guarantees every training value lands in a fixed range, which is exactly what some algorithms and some hardware paths require (a neural network with a bounded activation, a distance metric that assumes bounded inputs), but a single outlier in training compresses every other value into a tiny sliver of that range. Choosing between them is a decision about your data's distribution and your downstream algorithm's assumptions, not a coin flip.
A scaler fit at inference time is fit on whatever traffic happens to arrive in that batch — a handful of unusually large or small orders, or a single request in an online setting, which cannot even produce a meaningful mean or standard deviation on its own. The entire point of freezing the scaler's statistics during training is that every future prediction is measured against the same fixed reference frame the model was trained on. Recomputing those statistics at inference time silently changes that reference frame per batch, and the model starts seeing input that no longer means what it meant during training.
Given enough epochs and a small enough learning rate, gradient descent on unscaled features can eventually converge to a similar solution — but "eventually" is doing a lot of work in that sentence. An elongated, badly scaled loss surface forces gradient descent to zigzag rather than move directly toward the minimum, which in practice means far more iterations, a learning rate that has to be tuned much more carefully to avoid diverging, and training runs that are simply more expensive for no benefit. Scaling is not a correctness requirement for convergence in the limit; it is a practical requirement for training in a reasonable amount of time and compute budget.
For linear regression and tree-based models, the model simply adjusts its bias term or its leaf values to match whatever scale y happens to be on — scaling y changes nothing about the model's predictive accuracy, it just makes the coefficients look different. Scaling y earns its keep specifically for neural networks, where a target with a very large range can force the output layer into large weights and cause unstable training. Applying it everywhere by default, and then forgetting to inverse-transform predictions back to the original units before reporting an error metric, is a much more common bug than skipping it.
Feature scaling — 5 questions interviewers actually ask
Linear regression's coefficients and gradient descent updates are directly sensitive to the numeric magnitude of each feature — a feature with a much larger range dominates both the loss surface's shape and the size of its own coefficient, purely because of units, not because it is more predictive. Tree-based models instead pick a threshold and split the data on one feature at a time; whether that threshold happens to be 3.5 or 3,500 changes nothing about which rows end up on which side of the split or how pure the resulting leaves are. The split-finding logic is invariant to monotonic rescaling, so scaling has no effect on what the tree learns.
If you call fit on the scaler using the full dataset and only split into train and test afterward, the mean and standard deviation baked into the scaler were computed using test-set values. The training data is then scaled using statistics that partly describe data the model is supposed to have never seen, so evaluation metrics come out slightly optimistic — a subtle form of the model indirectly benefiting from test information. In a code review, the tell is the order of operations: look for any call to fit or fit_transform on a preprocessing step that happens before train_test_split, or any use of cross_val_score where the scaler was fit outside the cross-validation loop rather than wrapped inside a Pipeline.
I would default to StandardScaler when the feature is roughly normally distributed and the algorithm cares about comparable coefficient magnitudes — linear and logistic regression, SVMs, PCA — since it preserves the shape of the distribution while centring and rescaling it. I would reach for MinMaxScaler specifically when I need values bounded to a known range: feeding a neural network with a sigmoid or tanh activation, computing a similarity metric that assumes bounded inputs, or working with data like image pixels that is naturally bounded already. The deciding factor is usually whether downstream math requires a fixed range or just comparable scale.
Scaling assumes the live data still resembles the training distribution the scaler's mean and standard deviation were computed from. A gradual degradation with no code change is the classic signature of data drift — order values creep up with inflation, a marketing push changes the mix of delivery distances, a partner team quietly changes units upstream. I would compare the live distribution of each input feature against the distribution the scaler was fit on, specifically checking whether the live mean has drifted meaningfully from the frozen training mean, since that would mean the model is now seeing scaled values that no longer correspond to what it learned during training — and the fix is retraining, not patching the scaler in place.
Ridge and Lasso add a penalty term based directly on the size of each coefficient — Ridge penalises the sum of squared coefficients, Lasso the sum of absolute coefficients. A feature measured in a small-magnitude unit naturally gets a larger coefficient to produce the same effect on the prediction, and that larger coefficient then gets penalised more heavily purely because of its unit, not because it is less important. Unscaled features make the regularisation penalty unfair across features, shrinking some coefficients far more than others for reasons that have nothing to do with predictive value — scaling first is what makes the penalty apply comparably to every feature.
Scaling is now a reflex. Every algorithm you build from here uses it correctly.
StandardScaler inside a Pipeline, fit on training data only. This is the pattern you will repeat in every module from here. It takes three lines and prevents a class of subtle bugs that trip up even experienced practitioners.
Module 18 builds your first complete ML model from scratch: linear regression. You'll see how the scaled features from this module feed directly into the gradient descent update from Module 05, and how regularisation (Ridge and Lasso) prevents overfitting — with the coefficients directly interpretable as feature importance.
OLS, gradient descent, Ridge, Lasso, ElasticNet — and how to diagnose every failure mode on real delivery data.
🎯 Key Takeaways
- ✓Unscaled features distort gradient descent — features with large numerical ranges dominate weight updates. StandardScaler brings all features to mean=0, std=1, making gradient steps equal in all directions.
- ✓StandardScaler: x_scaled = (x − μ) / σ. Robust to most distributions. Use as the default for linear models, logistic regression, SVMs, K-means, PCA, and neural networks.
- ✓MinMaxScaler: x_scaled = (x − min) / (max − min). Produces values in [0,1]. Use when you need bounded output — neural network activations, cosine similarity, image pixels.
- ✓RobustScaler: x_scaled = (x − median) / IQR. Ignores outliers when computing the scaling statistics. Use when your data has significant outliers that should not distort the scale of the majority.
- ✓MaxAbsScaler divides by max absolute value — no mean subtraction. Use for sparse data (TF-IDF, one-hot) where zeroes must stay zero. Normalizer scales each row (sample) not each column (feature) — use for cosine similarity.
- ✓Tree-based algorithms (Decision Tree, Random Forest, XGBoost, LightGBM) do not need feature scaling — splits are threshold-based and scale-invariant. Scaling has no effect on their performance.
- ✓The only safe pattern: fit scaler on X_train only, transform both X_train and X_test. Use sklearn Pipeline to enforce this automatically in cross-validation. Never fit on the full dataset before splitting.
Discussion
0Have a better approach? Found something outdated? Share it — your knowledge helps everyone learning here.