TExcelTAD

Which Models Need Scaling

Scaling is not a ritual to apply to every dataset. Some models depend on feature scales, some do not at all, and knowing which is which saves work and avoids a common misunderstanding ("I standardised the features, so my random forest got better", when it could not have). The rule of thumb:

Model family Needs scaling? Why
kNN, k-means, DBSCAN, RBF SVM yes Euclidean distances: the largest-valued feature dominates
PCA yes finds directions of largest variance, so large-unit features win
Linear / logistic regression with regularisation (Ridge, Lasso, default LogisticRegression) yes one penalty strength for all coefficients is only fair on comparable scales
Linear regression without penalty for the fit, no; for the solver and the coefficient sizes, yes the predictions are the same, the coefficients just rescale
Neural networks, anything trained by gradient descent yes badly scaled inputs give a stretched loss surface and slow or unstable training
Decision trees, random forests, gradient boosting (XGBoost, LightGBM, HistGradientBoosting) no a split x <= t only depends on the order of values
Naive Bayes (Gaussian) no each feature gets its own mean and variance

Trees only see the order

A tree split asks "is income at most 42,300?". Any monotone transformation of income (scaling, log, square root, rank) keeps the same order of rows, so the same split exists with a transformed threshold, and the tree is unchanged. Let us check that claim directly:

python · try it yourself
import numpy as np
from sklearn.datasets import make_classification
from sklearn.preprocessing import QuantileTransformer, StandardScaler
from sklearn.tree import DecisionTreeClassifier

X, y = make_classification(n_samples=400, n_features=5, n_informative=3, random_state=0)
X = np.exp(X)                                   # skewed, positive features
X_train, X_test, y_train = X[:300], X[300:], y[:300]

variants = {
    "raw": (X_train, X_test),
    "standardised": (lambda s: (s.transform(X_train), s.transform(X_test)))(StandardScaler().fit(X_train)),
    "log": (np.log(X_train), np.log(X_test)),
}
preds = {}
for name, (tr, te) in variants.items():
    tree = DecisionTreeClassifier(max_depth=4, random_state=0).fit(tr, y_train)
    preds[name] = tree.predict(te)
    print(f"{name:13s} depth {tree.get_depth()}  leaves {tree.get_n_leaves()}  first test predictions {preds[name][:12].tolist()}")
print("identical predictions:", all((p == preds["raw"]).all() for p in preds.values()))
raw           depth 4  leaves 8  first test predictions [1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1]
standardised  depth 4  leaves 8  first test predictions [1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1]
log           depth 4  leaves 8  first test predictions [1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1]
identical predictions: True

The three trees have the same shape and make identical predictions on all 100 test rows. (In rare cases, ties between equally good splits can be broken differently after a transform, so "identical" is the rule, not a guarantee to the last row.) The same holds for random forests and gradient-boosted trees. Histogram-based boosting bins each feature by quantiles, which also depends only on order.

Note: "Trees don't need scaling" also means they don't need the log transform for skewed features. They do still need encoding for categories (depending on the library), and they still suffer from leakage like any other model.

Scaling and the models that need it

Now the same comparison across model families, with and without StandardScaler, on the breast-cancer data (569 tumours, 30 features with very different units), 5-fold stratified cross-validation:

python · try it yourself
import warnings
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import HistGradientBoostingClassifier, RandomForestClassifier
from sklearn.exceptions import ConvergenceWarning
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC

warnings.filterwarnings("ignore", category=ConvergenceWarning)
X, y = load_breast_cancer(return_X_y=True)
cv = StratifiedKFold(5, shuffle=True, random_state=0)
models = {
    "kNN (k=5)": KNeighborsClassifier(),
    "SVM (RBF)": SVC(),
    "logistic (L2, C=1)": LogisticRegression(max_iter=200),
    "random forest": RandomForestClassifier(n_estimators=100, random_state=0),
    "hist. gradient boosting": HistGradientBoostingClassifier(random_state=0),
}
print(f"{'model':24s} {'raw':>6s} {'scaled':>7s}")
for name, m in models.items():
    raw = cross_val_score(m, X, y, cv=cv).mean()
    scaled = cross_val_score(make_pipeline(StandardScaler(), m), X, y, cv=cv).mean()
    print(f"{name:24s} {raw:6.3f} {scaled:7.3f}")
model                       raw  scaled
kNN (k=5)                 0.932   0.965
SVM (RBF)                 0.921   0.977
logistic (L2, C=1)        0.956   0.979
random forest             0.965   0.965
hist. gradient boosting   0.970   0.970

The distance- and penalty-based models gain clearly: kNN goes from 0.932 to 0.965 accuracy and the RBF SVM from 0.921 to 0.977 (its kernel compares Euclidean distances, so on raw data the "area" features in the hundreds and thousands decide everything). Logistic regression also improves (0.956 to 0.979), partly because the solver does not converge on raw data within 200 iterations (we silenced that warning to keep the output short; in your own work, read it). The two tree ensembles score the same with and without scaling (0.965 and 0.970), as the previous example predicts.

Scaling and gradient descent

For models trained by gradient descent, scaling is mostly about speed and stability. With features on different scales, the loss surface is a narrow valley; a learning rate small enough for the steep direction crawls along the flat one. The gradient-descent lab shows such a valley. Counting solver iterations makes the cost visible:

python · try it yourself
import warnings
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.exceptions import ConvergenceWarning
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler

warnings.filterwarnings("ignore", category=ConvergenceWarning)
X, y = load_breast_cancer(return_X_y=True)
X_train, y_train = X[:400], y[:400]
for name, data in [("raw", X_train), ("standardised", StandardScaler().fit_transform(X_train))]:
    clf = LogisticRegression(max_iter=10000).fit(data, y_train)
    print(f"{name:13s} iterations to converge: {int(clf.n_iter_[0])}")
print("feature std ranges from", round(float(X_train.std(axis=0).min()), 4), "to", round(float(X_train.std(axis=0).max()), 1))
raw           iterations to converge: 2822
standardised  iterations to converge: 18
feature std ranges from 0.0029 to 582.5

The same model needs 2,822 iterations on raw data and 18 after standardisation: the feature standard deviations range from 0.003 to 583, a stretch factor of about 200,000. For a neural network the effect is the same, only larger, which is why inputs are standardised (and why networks contain normalisation layers inside, see batch normalisation).

Pitfalls

  • Scaling "because it can't hurt" for trees: it doesn't hurt the trees, but it adds a step that can leak if fitted outside the pipeline, and it makes thresholds harder to read.
  • Concluding a scaler helped a tree model: if scores change, look for another cause (a different random split, leakage, a bug).
  • Forgetting that one model in an ensemble or a stacked model needs scaling: a VotingClassifier of a forest and an SVM needs a scaled pipeline for the SVM.
  • Comparing coefficients of an unscaled linear model: a coefficient's size depends on the feature's unit. Compare standardised coefficients if you want "importance".

Practice

  1. You switch a pipeline from RandomForestClassifier to KNeighborsClassifier and forget the scaler. What do you expect?
Answer

A drop in accuracy whenever the features have different units: kNN's neighbours are then chosen mostly by the largest-valued features. Add StandardScaler (or another scaler) in front of kNN in the pipeline.

  1. Does Lasso need scaling? Why?
Answer

Yes. Lasso penalises the sum of the absolute coefficients with one strength. A feature measured in large units needs only a tiny coefficient and is barely penalised; one in small units needs a large coefficient and gets zeroed out first. Which features survive would depend on units, not on usefulness.

Test yourself

Why are decision trees unaffected by standardisation?

  1. They standardise internally
  2. Their splits only depend on the order of values, which a monotone transform keeps
  3. They ignore numeric features
  4. They use the median

Which of these models needs scaling most?

  1. Random forest
  2. Gradient-boosted trees
  3. k-nearest neighbours
  4. Decision tree

For logistic regression trained by an iterative solver, what does standardising mainly change?

  1. Nothing
  2. The number of iterations and the fairness of the regularisation penalty
  3. The number of classes
  4. The labels