
When Feature Scaling Changes Your Results, and When It Doesn't
- كاتب موثّق
- scikit-learn 1.9
محتويات المقال
StandardScaler. Someone else objects: "Scaling doesn't change the information. We tried it on the churn random forest and nothing moved." Both observations are true, and they're about different kinds of models.
The common misconception
Scaling loses no information. Each column keeps its order and the relative spacing of its values, so it feels like changing units from meters to kilometers. Tree-based models, a common first choice for tabular data, really are unaffected. Anyone who tried scaling with a random forest saw identical numbers. Tutorials often add StandardScaleras a ritual step without saying why, so it looks like hygiene, like formatting code.
What actually happens
StandardScaler, the usual choice, gives each feature a mean of 0 and a standard deviation of 1. Whether that matters depends on how the model uses the numbers.
Same data, five models
from sklearn.datasets import load_winefrom sklearn.model_selection import StratifiedKFold, cross_val_scorefrom sklearn.neighbors import KNeighborsClassifierX, y = load_wine(return_X_y=True)print(X[:, 12].max(), X[:, 10].max()) # proline 1680.0, hue 1.71# "Scaling is cosmetic": KNN on the raw columnscv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)score = cross_val_score(KNeighborsClassifier(), X, y, cv=cv).mean()print(f"KNN on raw features: {score:.3f}") # 0.663from sklearn.datasets import load_winefrom sklearn.ensemble import RandomForestClassifierfrom sklearn.linear_model import LogisticRegressionfrom sklearn.model_selection import StratifiedKFold, cross_val_scorefrom sklearn.neighbors import KNeighborsClassifierfrom sklearn.pipeline import make_pipelinefrom sklearn.preprocessing import StandardScalerfrom sklearn.svm import SVCfrom sklearn.tree import DecisionTreeClassifierX, y = load_wine(return_X_y=True)cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)for model in [KNeighborsClassifier(), SVC(), LogisticRegression(max_iter=5000), DecisionTreeClassifier(random_state=0), RandomForestClassifier(random_state=0)]: raw = cross_val_score(model, X, y, cv=cv).mean() pipe = make_pipeline(StandardScaler(), model) # scaler fit per fold scaled = cross_val_score(pipe, X, y, cv=cv).mean() print(f"{type(model).__name__:<23} raw {raw:.3f} scaled {scaled:.3f}")# KNeighborsClassifier raw 0.663 scaled 0.961# SVC raw 0.657 scaled 0.983# LogisticRegression raw 0.955 scaled 0.983# DecisionTreeClassifier raw 0.927 scaled 0.927# RandomForestClassifier raw 0.972 scaled 0.972Distances: the biggest column wins
Penalties: regularization depends on units
LogisticRegression applies an L2 penalty by default, which shrinks all weights by the same rule. A feature measured in large units needs only a tiny weight, so it barely gets penalized, while small-unit features get squeezed. The scikit-learn preprocessing guide warns that such penalties may assume features have variance of the same order, and that a feature with a much larger variance can dominate the objective. Here, logistic regression moves from 0.955 to 0.983. With the default max_iter=100, the unscaled version doesn't even finish: the lbfgs solver reports that it failed to converge after 100 iterations.
Gradient steps: one learning rate for every feature
SGDClassifier to neural networks, use a single learning rate across all weights. Google's Machine Learning Crash Course lists what normalization buys you there: faster convergence, avoiding the "NaN trap" when values are very large, and letting the model learn appropriate weights for each feature.
Trees: only the order matters
HistGradientBoostingClassifier behave the same way, because they bin each feature by the order of its values.
How to apply it in your project
Check your model family Use the table above. If your model compares features through distances, penalties or gradient steps, scaling is part of the model, not cosmetics. Put the scaler in a pipeline Use make_pipeline(StandardScaler(), model)so cross-validation fits the scaler on each training fold only.Choose the scaler by distribution Start with StandardScaler, switch toRobustScalerfor heavy outliers, and log-transform power-law features first.Measure both versions Run the same cross-validation with and without the scaler, as in the script above. It's a one-line change. Save the whole pipeline Persist the fitted pipeline, scaler included, so production inputs get exactly the training-time transformation.
Key takeaways
Scaling keeps the information within each column but changes how models compare columns. Distance-based models, regularized linear models and gradient-trained models need it; on the wine data, KNN went from 0.663 to 0.961. Tree-based models only use the order of values, so scaling leaves them unchanged. Fit the scaler on training data inside a pipeline, and ship it with the model.
التعليقات (0)