Sub topic 16
Support vector regression
This chapter assumes you know the soft-margin SVM, the hinge loss, the role of C, support vectors, and the kernel trick from the earlier chapters. You should also be comfortable with scikit-learn pipelines and cross-validation.
Support vector regression (SVR) applies the maximum-margin idea to a continuous target. It keeps the same ingredients as the classifier: a regularized linear model, slack variables, a dual problem, and kernels. What changes is the loss function.
From classification margin to a regression tube
A classifier wants every point on the correct side of the boundary, with a margin. A regressor has no sides. SVR instead asks for a function f(x) = w·x + b that stays within a distance ε of every target value, while keeping w as small as possible. The region |y − f(x)| ≤ ε is called the ε-tube.
Keeping ‖w‖ small makes the function flat, so it does not chase noise. This is the same regularization argument that produces a large margin in classification.
Points inside the tube cost nothing. Points outside pay for how far outside they are. Two slack variables per point, ξᵢ and ξᵢ*, measure the overshoot above and below the tube.
The ε-insensitive loss
The loss is zero for small errors and linear for large ones:
L_ε(y, f(x)) = max(0, |y − f(x)| − ε)
The primal problem is:
- Minimize 0.5·‖w‖² + C·Σ(ξᵢ + ξᵢ*)
- Subject to yᵢ − (w·xᵢ + b) ≤ ε + ξᵢ
- Subject to (w·xᵢ + b) − yᵢ ≤ ε + ξᵢ*
- Subject to ξᵢ, ξᵢ* ≥ 0
The code below computes the loss and the objective directly, which is useful for checking intuition.
import numpy as np
def eps_insensitive(residual, epsilon):
return np.maximum(0.0, np.abs(residual) - epsilon)
def svr_objective(w, b, X, y, C, epsilon):
residual = y - (X @ w + b)
return 0.5 * np.dot(w, w) + C * eps_insensitive(residual, epsilon).sum()
residuals = np.array([-3.0, -1.0, 0.0, 0.5, 2.0])
print(eps_insensitive(residuals, epsilon=1.0))The output is [2. 0. 0. 0. 1.]. Only the residuals −3 and 2 fall outside the tube of half-width 1.
Compare this with squared error, which penalizes every residual and grows quadratically. The linear tails also make SVR less sensitive to outliers than ordinary least squares.
Support vectors in regression
The KKT conditions work as they do for classification, with a different meaning:
- Points strictly inside the tube have zero dual coefficients. They do not affect the fit.
- Points on the tube boundary or outside it have nonzero coefficients. These are the support vectors.
The dual coefficient for each point is αᵢ − αᵢ*. It is bounded by C in absolute value. Predictions use only the support vectors:
f(x) = Σ (αᵢ − αᵢ*)·K(xᵢ, x) + b
A larger ε means a wider tube, fewer points outside it, and fewer support vectors. This gives a smoother and sparser model. A smaller ε fits the data more tightly and uses more support vectors.
Note that with ε = 0 almost every point becomes a support vector, and the model is close to a regularized absolute-error fit.
The three hyperparameters
SVR has three main knobs, and they interact.
| Parameter | Controls | Too small | Too large |
|---|---|---|---|
| C | Penalty for points outside the tube | Underfits, nearly flat line | Overfits, follows noise |
| epsilon | Tube half-width, in target units | Many support vectors, noisy fit | Flat model, high bias |
| gamma (RBF) | Reach of each support vector | Smooth, nearly linear | Spiky, memorizes points |
The key difference from classification is that ε is measured in the units of y. The default epsilon=0.1 is meaningful only if y has a scale near 1. If y ranges over hundreds, a tube of 0.1 is effectively zero. If y ranges within 0.01, a tube of 0.1 swallows all the data and the model predicts a constant.
A working example with target scaling
Feature scaling matters for the same reasons as in classification, because the RBF kernel uses distances. In regression you should usually scale the target as well. TransformedTargetRegressor does this and undoes the scaling at prediction time.
import numpy as np
from sklearn.compose import TransformedTargetRegressor
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVR
rng = np.random.RandomState(0)
X = np.sort(rng.uniform(0, 5, 300))[:, None]
y = 100 * np.sin(X).ravel() + rng.normal(0, 10, 300)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
model = TransformedTargetRegressor(
regressor=make_pipeline(StandardScaler(), SVR(kernel="rbf", C=10, epsilon=0.1)),
transformer=StandardScaler(),
)
model.fit(X_train, y_train)
svr = model.regressor_.named_steps["svr"]
print("support vectors:", svr.support_.size, "of", len(X_train))
print("test R^2:", round(model.score(X_test, y_test), 3))Here epsilon=0.1 is in scaled target units, which is about 0.1 standard deviations. The model reports support_ (indices of support vectors) and dual_coef_ (the αᵢ − αᵢ* values), as the classifier does.
Tuning
Tune C, ε, and gamma together with cross-validated grid search, using the pipeline above. Parameter names reach through the wrapper with the regressor__ prefix.
from sklearn.model_selection import GridSearchCV
param_grid = {
"regressor__svr__C": [1, 10, 100],
"regressor__svr__epsilon": [0.01, 0.1, 0.3],
"regressor__svr__gamma": [0.1, 1, 10],
}
grid = GridSearchCV(model, param_grid, cv=5, scoring="neg_mean_absolute_error")
grid.fit(X_train, y_train)
print(grid.best_params_)
print("test MAE:", -grid.score(X_test, y_test))Choose a scoring metric that matches the loss you care about. Mean absolute error pairs naturally with ε-insensitive loss. A practical way to set the ε range is to base it on the noise level: if you expect noise with standard deviation σ in scaled units, values of ε up to about σ are reasonable candidates.
Variants in scikit-learn
SVRis the kernelized version, solved with libsvm. It supports linear, polynomial, RBF, and sigmoid kernels.NuSVRreplaces ε with a parameter ν in (0, 1]. ν sets a lower bound on the fraction of support vectors and an upper bound on the fraction of points outside the tube. The tube width is then found automatically.LinearSVRfits only a linear model with liblinear. It scales to far more samples, but it has no kernel and it penalizes the intercept by default, so checkintercept_scaling.
Common errors
- Unscaled target with default ε. The fit is either a constant or nearly an exact interpolation, depending on the scale. Scale y or set ε explicitly.
- Forgetting features need scaling. One large-range feature dominates the RBF distance.
- Reading all support vectors as outliers. In SVR, support vectors include points on the tube edge. A model with many support vectors is not necessarily overfit, but one where nearly every point is a support vector is slow and often too flexible.
- Expecting uncertainty estimates. SVR gives a point prediction only. It has no
predict_probaequivalent and no built-in prediction interval. - Large datasets. Kernel SVR training grows between quadratically and cubically with the number of samples, and prediction cost grows with the number of support vectors. Beyond tens of thousands of samples, consider
LinearSVR, kernel approximations, or tree ensembles.
Exercise
You fit SVR(epsilon=0.1) on house prices measured in dollars (values around 300000) without scaling y, and the model predicts nearly the same value for every house. Give the likely cause and two ways to fix it.
Show answer
The tube half-width of 0.1 dollars is tiny compared with the price scale, and the default C is small relative to the target magnitudes. The regularization term dominates, so the fitted function is nearly flat. Fix it by scaling the target (for example with TransformedTargetRegressor and StandardScaler, or by modeling prices in thousands) and then tuning C and epsilon on the scaled target. Increasing C also reduces flatness, but scaling the target is the cleaner fix.
Exercise
You increase epsilon from 0.05 to 0.5 while keeping C and gamma fixed. What happens to the number of support vectors and to the bias and variance of the model?
Show answer
The tube gets wider, so more training points fall strictly inside it and have zero dual coefficients. The number of support vectors falls. The model becomes smoother and sparser, so variance drops and bias rises.