Sub topic 12
Scaling features before fitting
This chapter assumes you know the RBF and linear kernels, the role of C and gamma, and how a scikit-learn Pipeline works. It covers why SVMs need scaled features and how to scale them without leaking test data.
Why SVMs are sensitive to scale
An SVM works with distances and dot products between points. The RBF kernel uses ||x_i - x_j||^2, and the linear kernel uses x_i . x_j. If one feature ranges over thousands and another over fractions, the large feature dominates both quantities. The margin is then effectively measured along that one axis, and the small feature has almost no influence.
Scale also affects regularization. The penalty 0.5*||w||^2 is not the same for every feature. A feature with large values needs only a small weight, so it is penalized lightly. A feature with small values needs a large weight, so it is penalized heavily. Unscaled data therefore makes the model favor large-valued features for reasons unrelated to how useful they are.
Standardizing
The usual fix is standardization. Each feature is shifted to mean 0 and divided by its standard deviation. The mean and standard deviation come from the training data only.
Gamma is easiest to reason about after this step. With standardized features, a gamma near 1 / n_features is a sensible starting scale, which is close to scikit-learn's gamma="scale" default.
A demonstration
The example below adds one feature with a huge range and compares an unscaled SVM with a scaled one.
import numpy as np
from sklearn.datasets import make_moons
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 = make_moons(n_samples=400, noise=0.25, random_state=0)
X[:, 1] *= 1000 # second feature now spans thousands
raw = SVC(kernel="rbf", gamma=0.5)
scaled = make_pipeline(StandardScaler(), SVC(kernel="rbf", gamma=0.5))
print("unscaled:", cross_val_score(raw, X, y, cv=5).mean())
print("scaled: ", cross_val_score(scaled, X, y, cv=5).mean())The unscaled model has to rely almost entirely on the inflated feature, so its accuracy is clearly lower. The scaled pipeline recovers the accuracy of the original data.
Common errors
- Fitting the scaler on all the data. Scaling before the train and test split lets test statistics leak into training. Put the scaler in a pipeline so each cross-validation fold fits it on the training part only.
- Scaling train and test separately. The test set must use the training mean and standard deviation. Call
transform, notfit_transform, on new data. - Scaling one-hot columns blindly. Standardizing binary columns is usually harmless, but it changes their weight in the kernel. Treat it as a choice to test.
- Ignoring sparse data.
StandardScaler(with_mean=False)orMaxAbsScalerkeeps sparse matrices sparse.
Exercise
You standardize the full dataset, then split it into train and test sets, then run grid search on the training set. What is wrong, and how do you fix it?
Show answer
The scaler saw the test data when it computed the mean and standard deviation, so information leaks from test into training. Split first, then put StandardScaler and SVC in a pipeline and pass the pipeline to GridSearchCV. Each fold then fits the scaler only on its own training part.