Sub topic 2
Which models need scaling and which do not
This chapter assumes you know basic NumPy and scikit-learn estimators, the idea of a train/test split, and what mean and standard deviation measure. The previous chapter showed that features can sit on very different scales. Here you will learn which models that matters for, and why.
The rule of thumb
A model needs scaling when it compares the size of feature values across columns. A model does not need scaling when it only looks at the order of values within one column.
Scaling by standardization or min-max is a monotonic transformation per column. It keeps the ordering of values inside a column and changes only their magnitudes. Models that use only ordering ignore the change. Models that use magnitudes are affected.
Three ways scale causes trouble
Distance-based models
k-nearest neighbors, k-means, and SVMs with an RBF kernel all compute distances between rows. Euclidean distance adds up squared differences across columns:
d² = (Δage)² + (Δincome)²
If age differs by 10 years and income differs by 5,000 dollars, the income term is 250,000 times larger than the age term. Age effectively disappears from the distance.
Gradient-based models
Linear and logistic regression trained by gradient descent, and neural networks, update weights using gradients. When one feature has a much larger range, the loss surface becomes a long, narrow valley. The learning rate that is safe for the large feature is too small for the small one, so training is slow or unstable. Scaled features give a rounder surface and faster convergence.
Regularized models
Ridge, lasso, and elastic net penalize the size of coefficients. A feature measured in small units needs a large coefficient to have the same effect, so it is penalized more. The penalty then depends on the units you happened to choose. Scaling makes the penalty treat all features equally.
PCA belongs in this group too. It looks for directions of maximum variance, and a feature with a large numeric range dominates the first component.
Models that do not need scaling
Decision trees, random forests, and gradient-boosted trees choose splits of the form feature <= threshold. Rescaling a column moves the thresholds but leaves the same row partitions available, so the tree structure is unchanged. Gaussian naive Bayes fits each feature separately, so scale does not change its predictions either.
Ordinary least squares is a special case. Predictions are identical with or without scaling, but the coefficients change, so scale matters if you want to compare coefficients.
| Model family | Examples | Needs scaling? | Reason |
|---|---|---|---|
| Distance-based | kNN, k-means, RBF SVM | Yes | Distances mix columns |
| Gradient-trained | Logistic regression, neural nets | Yes | Conditioning of the loss surface |
| Penalized linear | Ridge, lasso, elastic net | Yes | Penalty depends on units |
| Variance-based | PCA | Yes | Large ranges dominate components |
| Tree-based | Decision tree, random forest, boosting | No | Splits use order only |
| Per-feature probabilistic | Gaussian naive Bayes | No | Each column modeled separately |
| Unpenalized least squares | LinearRegression | Not for predictions | Coefficients rescale, fit does not change |
See the difference
The wine dataset has features ranging from about 0.1 to over 1,600 (proline). The code below compares kNN and a decision tree with and without a StandardScaler. The scaler sits inside a pipeline so it is refit on each training fold. Pipelines are covered in a later chapter.
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
from sklearn.tree import DecisionTreeClassifier
X, y = load_wine(return_X_y=True)
models = {
"kNN, raw": KNeighborsClassifier(),
"kNN, scaled": make_pipeline(StandardScaler(), KNeighborsClassifier()),
"tree, raw": DecisionTreeClassifier(random_state=0),
"tree, scaled": make_pipeline(StandardScaler(), DecisionTreeClassifier(random_state=0)),
}
for name, model in models.items():
score = cross_val_score(model, X, y, cv=5).mean()
print(f"{name:14s} {score:.3f}")Expect the scaled kNN score to be clearly higher than the raw one, because proline dominates the raw distances. The two tree scores should be equal or very close, since scaling does not change which splits are available.
A decision flow
Common mistakes
- Scaling for a tree model and expecting better accuracy. The ordering is unchanged, so accuracy will not improve.
- Forgetting that a regularized model's penalty strength depends on scale. A value of
alphathat works on raw data may behave very differently after scaling, so tune it again. - Comparing coefficients of an unscaled linear model as a measure of feature importance. The coefficient size reflects the units.
Exercise
A teammate fits a RandomForestClassifier on raw features and a Ridge regression on the same raw features. Which model would you expect to change its behavior if you standardized the inputs, and why?
Show answer
Ridge would change. Its penalty is applied to coefficient size, which depends on feature units, so standardizing changes which coefficients are shrunk and by how much. The random forest uses only the ordering of values within each column to choose splits, so standardizing leaves its possible splits unchanged.
Exercise
In a kNN model, feature A ranges from 0 to 1 and feature B ranges from 0 to 10,000. Which feature dominates the distance, and which scaler would fix it?
Show answer
Feature B dominates, because its differences are far larger than those of A in the squared-distance sum. Either StandardScaler or MinMaxScaler puts both features on comparable scales, so both contribute to the distance.