Sub topic 2
Which Models Need Scaling and Which Do Not
This chapter assumes you know basic NumPy, mean and standard deviation, and the split into training and test sets. It also assumes you have used a scikit-learn estimator with fit and predict. The scalers themselves are covered in later chapters. Here you will learn which models care about feature scale and why. That tells you when scaling is needed and when it is wasted effort.
The short version
Scaling matters when a model does one of three things with raw feature values:
- It computes distances between rows.
- It optimizes its parameters with gradient steps.
- It penalizes the size of its coefficients.
Scaling does not matter for models that only compare a feature to a threshold, such as decision trees and the ensembles built from them.
Each mechanism fails in its own way, so it helps to know all three.
Mechanism 1: distances
Many models decide what is "similar" by measuring distance between rows. The common choice is Euclidean distance, the straight-line distance between two points:
d = sqrt((a1 - b1)^2 + (a2 - b2)^2 + ...)
Each feature contributes its squared difference. A feature measured in thousands produces much larger differences than a feature measured in tens, so it takes over the sum.
Take two people described by age (years) and income (dollars):
- Person A: age 30, income 50000
- Person B: age 40, income 51000
The age difference is 10 and the income difference is 1000. The distance is sqrt(10^2 + 1000^2), which is about 1000.05. Age contributes almost nothing. Person B would also look "closer" to A than a 31-year-old earning 52000 would, even though that person is far more similar in age. The model has effectively dropped the age column.
Models that depend on distance include:
- k-nearest neighbors (KNN), for both classification and regression.
- k-means and other clustering methods that use distance.
- Support vector machines with an RBF kernel. The kernel is a function of the squared distance between points.
- Principal component analysis (PCA). It looks for directions of maximum variance, so a feature with a large numeric range dominates the first components.
Here is the effect on a real dataset. The wine dataset has 13 chemical measurements. One of them, proline, ranges from a few hundred to over 1600, while others stay below 10.
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())Expect a large gap in favor of the scaled model. The exact numbers depend on your scikit-learn version, but the raw model is far worse. The make_pipeline call keeps the scaler inside each cross-validation fold. A later chapter explains why that matters, so for now treat it as the safe way to combine a scaler and a model.
Mechanism 2: gradient-based optimization
Linear models, logistic regression, and neural networks are often fitted by gradient descent. This is an iterative method that adjusts the parameters in small steps downhill on a loss function. Features on very different scales make the loss surface a long, narrow valley. A step size that suits one parameter is too large for another, so the optimizer zigzags and converges slowly, or not at all.
You see this in scikit-learn as a ConvergenceWarning. Logistic regression with the default lbfgs solver and unscaled features often stops at max_iter before it converges. Standardizing the features usually fixes this without raising max_iter.
Two details are worth knowing:
- Some solvers are less sensitive than others. Closed-form ordinary least squares does not iterate, so it does not suffer from slow convergence.
- Stochastic gradient methods (
SGDClassifier,SGDRegressor) and neural networks (MLPClassifier) are very sensitive. Their step sizes are fixed or follow a schedule, and they cannot adapt to each feature's range.
Mechanism 3: regularization
Regularization adds a penalty on the size of the coefficients to the loss. Ridge (L2) penalizes the sum of squared coefficients. Lasso (L1) penalizes the sum of absolute values. Elastic net mixes the two. LogisticRegression applies an L2 penalty by default, controlled by C.
A coefficient's size depends on the units of its feature. A feature in millimeters needs a coefficient 1000 times smaller than the same feature in meters to have the same effect. The penalty only sees the coefficient, so it punishes the meters version far more than the millimeters version, although the two carry identical information. Unscaled features are therefore shrunk unevenly, and in lasso they are dropped unevenly.
import numpy as np
from sklearn.linear_model import Ridge
rng = np.random.default_rng(0)
x_a = rng.normal(size=200)
x_b = rng.normal(size=200)
y = x_a + x_b + rng.normal(scale=0.5, size=200)
# Feature b is stored in units 1000 times smaller, so its column is 1000 times larger
X = np.column_stack([x_a, x_b * 1000])
model = Ridge(alpha=100).fit(X, y)
# Coefficient times feature spread shows how much each feature contributes
print(model.coef_ * X.std(axis=0))Both features have the same true effect, so the two printed values should be about equal. They are not. The first is noticeably shrunk, roughly to two thirds of its true contribution. The second stays close to 1.0, because its coefficient is tiny (about 0.001) and the penalty barely touches it. Scaling both columns first makes the penalty treat them equally.
Models that do not need scaling
Decision trees choose a feature and a threshold at each split, such as proline <= 755. The split depends only on how the values are ordered, not on how far apart they are. Any strictly increasing transformation of a feature, including standardization and min-max scaling, preserves that order. The tree finds the same partitions with thresholds expressed in the new units.
Random forests, extra trees, and gradient boosting (including HistGradientBoostingClassifier, XGBoost, and LightGBM) are built from trees, so they inherit this property.
You can check this directly:
import numpy as np
from sklearn.datasets import load_wine
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.tree import DecisionTreeClassifier
X, y = load_wine(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, random_state=0
)
scaler = StandardScaler().fit(X_train)
tree_raw = DecisionTreeClassifier(random_state=0).fit(X_train, y_train)
tree_scaled = DecisionTreeClassifier(random_state=0).fit(
scaler.transform(X_train), y_train
)
pred_raw = tree_raw.predict(X_test)
pred_scaled = tree_scaled.predict(scaler.transform(X_test))
print(np.array_equal(pred_raw, pred_scaled))This should print True. In rare cases, ties between equally good splits or floating-point rounding can change a prediction. That is a tie-breaking effect, not a real difference in what the model learns.
A reference table
| Model family | Sensitive to scale? | Reason |
|---|---|---|
| KNN, radius neighbors | Yes | Euclidean distance between rows |
| k-means, DBSCAN, hierarchical clustering | Yes | Distance-based grouping |
| SVM (RBF, polynomial kernels) | Yes | Kernels depend on distances or dot products |
| PCA | Yes | Maximizes variance, which depends on units |
| Neural networks, SGD-based models | Yes | Gradient steps and weight initialization assume similar ranges |
| Ridge, lasso, elastic net, regularized logistic regression | Yes | The penalty acts on coefficient size |
| Ordinary least squares | Predictions no, coefficients yes | Closed-form fit is equivariant to rescaling, but coefficient values change |
| Decision tree, random forest, gradient boosting | No | Splits depend only on feature order |
| Gaussian naive Bayes | Mostly no | Each feature has its own fitted mean and variance |
The ordinary least squares row has a trap. Rescaling a feature leaves the fitted predictions unchanged, because the coefficient simply rescales to compensate. But you cannot compare raw coefficients across features to judge importance. Standardized features make the coefficients comparable, which is a reason to scale even when the predictions would not change.
Deciding in practice
Two situations call for extra thought:
- A mixed workflow. If you compare a random forest and a KNN model on the same data, the forest does not need scaling but the KNN model does. Put the scaler inside the KNN pipeline only. Scaling the shared data for everyone is harmless to the forest but easy to get wrong, because it can leak information, as a later chapter shows.
- Interpretation. You may want to read feature importance from a tree in original units, such as "split at proline 755". Scaling does not change the model but it does change the printed thresholds. Use
inverse_transform, covered in a later chapter, or skip scaling for those models.
Common errors
- Scaling a tree model out of habit. It costs a step and gives no gain. It also adds a place for leakage mistakes.
- Skipping scaling for a regularized model because "it is just linear". The penalty makes it scale-sensitive even though ordinary least squares is not.
- Scaling the target in classification. Class labels are not features. Do not scale
y. - Scaling one-hot columns without thinking. One-hot columns are already 0 or 1. Standardizing them is allowed, but it makes them less readable and can distort sparse data. Decide on purpose, not by default.
- Assuming scaling fixes every ill-behaved feature. It changes range, not shape. A heavily skewed feature stays skewed after standardization.
Summary
Check each model for the three mechanisms. If it measures distances, takes gradient steps, or penalizes coefficients, give it scaled features. If it only splits on thresholds, leave the features alone. Ordinary least squares sits in between: predictions do not change, but coefficient comparisons do. The next chapters show how to do the scaling itself.
Exercise
You are building two models on the same table of numeric features: a random forest and an L2-regularized logistic regression. Which one needs scaled features, and why? What happens if you scale for both?
Show answer
The regularized logistic regression needs scaling. Its penalty acts on coefficient size, and coefficient size depends on feature units, so unscaled features are shrunk unevenly. The solver also converges faster on scaled features. The random forest only compares features to thresholds, so its splits depend on feature order, and scaling does not change them. Scaling for both is harmless to the forest's predictions, but the scaler must still be fitted on training data only. The cleanest design puts the scaler in a pipeline for the logistic regression and leaves the forest unscaled.
Exercise
Two features, age (20 to 60) and income (20000 to 120000), are fed to KNN with Euclidean distance. Roughly which feature decides which neighbors are nearest, and what would you do about it?
Show answer
Income decides it. Differences in income are in the thousands, so their squares dwarf age differences of at most 40, and age has almost no effect on the distance. Standardize or min-max scale both features, ideally in a pipeline in front of the KNN model, so each contributes comparably to the distance.