Sub topic 12
Scaling features before fitting
This chapter explains why SVMs are sensitive to feature scale, how to pick a scaler, and how to apply it without leaking test information. It assumes you can fit an SVC in scikit-learn and know what the RBF kernel and the parameters C and gamma do. It also assumes you know what cross-validation is.
Why SVMs care about scale
An SVM works on geometry. The margin is measured as a Euclidean distance in feature space. The RBF kernel is exp(-gamma * ||x - x'||^2), and the polynomial kernel uses dot products. Every one of these quantities adds up contributions from all features with equal weight. If one feature is measured in the tens of thousands and another between 0 and 1, the large feature dominates every distance, and the small one has almost no influence.
The numbers below show the effect on two points described by income and age.
import numpy as np
a = np.array([50_000.0, 25.0])
b = np.array([52_000.0, 60.0])
sq = (a - b) ** 2
print("squared difference per feature:", sq)
print("share of distance from age: %.4f%%" % (100 * sq[1] / sq.sum()))Age contributes about 0.03% of the squared distance, even though a 35-year gap is large. The RBF kernel treats these two people as "close" because of income alone, whatever gamma you choose.
A second effect comes from regularization. The soft-margin objective penalizes 0.5 * ||w||^2 uniformly across weights. A feature with a small numeric range needs a large weight to matter, and the penalty makes large weights expensive. So the model is biased against small-range features even when they are the informative ones.
Seeing the effect on real data
The breast cancer dataset has features that range from about 0.05 to over 2,500. Compare an unscaled SVM with a scaled one under the same cross-validation.
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
X, y = load_breast_cancer(return_X_y=True)
raw = SVC(kernel="rbf")
scaled = make_pipeline(StandardScaler(), SVC(kernel="rbf"))
print("raw :", cross_val_score(raw, X, y, cv=5).mean().round(3))
print("scaled:", cross_val_score(scaled, X, y, cv=5).mean().round(3))The scaled pipeline scores clearly higher. The exact numbers depend on your scikit-learn version, so run it yourself.
The default gamma="scale" in SVC sets gamma to 1 / (n_features * X.var()). This adjusts for the overall spread of the data, so it avoids the worst case where one global gamma is far too large or small. It cannot fix differences between individual features, so you still need to scale.
Choosing a scaler
| Scaler | What it does | Use when |
|---|---|---|
| `StandardScaler` | Subtracts the mean, divides by the standard deviation | Default choice for RBF and polynomial kernels. Works best on roughly bell-shaped features |
| `MinMaxScaler` | Maps each feature to a fixed range, usually [0, 1] | Features are bounded, or you want a known range. Sensitive to outliers |
| `RobustScaler` | Subtracts the median, divides by the interquartile range | Features have outliers that would distort the mean and standard deviation |
| `MaxAbsScaler` | Divides by the maximum absolute value | Sparse data, because it keeps zeros as zeros |
The choice of scaler matters less than the decision to scale at all. If StandardScaler works, you can try RobustScaler as a check when your data has heavy outliers.
Outliers
With StandardScaler and MinMaxScaler, one extreme value inflates the standard deviation or the range. The remaining points are then squeezed into a narrow band. Squeezed features lose influence, which brings back the problem scaling was meant to fix. Inspect feature distributions, and consider RobustScaler or a log transform for heavy-tailed features such as prices or counts.
Sparse data
StandardScaler subtracts the mean by default. On a sparse matrix this would turn most zeros into nonzero values, so scikit-learn raises an error. Use StandardScaler(with_mean=False) or MaxAbsScaler. For text features such as TF-IDF, the rows are already normalized, and a linear SVM usually works without further scaling.
Binary and one-hot columns
A one-hot column is already on a 0 to 1 scale. Applying StandardScaler to a rare category gives its nonzero entries a large value, and that increases its influence. Whether this is desirable depends on the problem. A common safe approach is to scale only the numeric columns with a ColumnTransformer and leave the one-hot columns alone.
Constant features
A feature with zero variance carries no information. StandardScaler handles it without a division by zero, because it uses a scale of 1 for such columns. It then stays constant at 0 and has no effect on the SVM.
Scale inside the cross-validation loop
The scaler learns its mean and standard deviation from data. If you fit it on the full dataset before splitting, the test fold's statistics leak into training. The estimate becomes slightly optimistic, and the effect is larger on small datasets.
The correct manual procedure fits the scaler on the training data only, then applies it to the test data.
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, random_state=0, stratify=y
)
scaler = StandardScaler().fit(X_train) # statistics from training data only
clf = SVC(kernel="rbf").fit(scaler.transform(X_train), y_train)
print("test accuracy:", clf.score(scaler.transform(X_test), y_test))A Pipeline automates this and also repeats it correctly in every cross-validation fold. This is why the grid search in the tuning chapter puts StandardScaler inside the pipeline.
Interactions with other choices
Scaling changes which values of C and gamma work well. A grid that was good for raw features is usually wrong after scaling, so scale first and then tune. On standardized data, gamma values between 0.001 and 10 on a logarithmic grid are a reasonable start, because typical squared distances are of the order of the number of features.
For regression with SVR, the target also affects the result. The epsilon tube width and C are in the units of y. If the target is very large or small, scale it as well, for example with TransformedTargetRegressor.
LinearSVC has the same sensitivity. It regularizes the intercept too, and it can fail to converge on unscaled data. A ConvergenceWarning there is often a sign that scaling is missing.
Tree-based models such as random forests do not need scaling, because they only compare values within one feature. Do not assume the same holds for SVMs.
Exercise
You standardize the whole dataset with StandardScaler().fit_transform(X), then run 5-fold cross-validation on an SVC. What is wrong with this, and how do you fix it?
Show answer
The scaler's mean and standard deviation were computed using all rows, including the rows that become validation folds, so information from the validation data leaks into training and the score is optimistic. Put the scaler and the SVM in a make_pipeline(StandardScaler(), SVC()) and pass the pipeline to cross_val_score. Then the scaler is fit on the training part of each fold only.
Exercise
A dataset has a feature "annual income" with a few extreme billionaires, plus several features between 0 and 1. You use MinMaxScaler and the RBF SVM performs poorly. Why, and what would you try?
Show answer
The billionaires set the maximum, so almost all other incomes map to values very close to 0. That feature then has little influence on distances. Try RobustScaler, which uses the median and interquartile range, or apply a log transform to income before scaling.