Sub topic 10
Choosing a kernel: linear, polynomial, RBF
This chapter assumes you know the soft-margin SVM, the role of C, and the dual form where training data appears only through dot products. It also assumes you can read basic scikit-learn code. You will compare the three most common kernels, learn what each parameter does, and pick one with a repeatable procedure.
What a kernel choice means
The dual problem uses the data only through the values K(x_i, x_j). A kernel is a function that returns the dot product of two points after a feature map phi, without computing phi itself:
K(x, z) = phi(x) · phi(z)
Choosing a kernel therefore chooses the feature space in which the SVM looks for a maximum-margin hyperplane. The boundary is linear in that space and usually nonlinear in the original one. The decision function is:
f(x) = sum_i alpha_i y_i K(x_i, x) + b
The sum runs over support vectors only.
The linear kernel
The linear kernel is K(x, z) = x · z. The feature map is the identity, so the boundary is a hyperplane in the original space.
- It has no kernel parameter. Only C needs tuning.
- It gives a weight vector
wyou can inspect (coef_in scikit-learn), so each feature's influence is readable. - It is the best default when there are many features relative to samples, for example text with TF-IDF features. In high dimensions, data is often close to linearly separable already.
- For large datasets,
LinearSVCorSGDClassifierscales far better thanSVC(kernel="linear").
The polynomial kernel
The polynomial kernel is:
K(x, z) = (gamma * x · z + coef0) ** degree
It implicitly includes all feature products up to the given degree. With two features and degree 2, the implicit features include x1^2, x2^2, and x1*x2. A quadratic boundary such as an ellipse becomes a plane in that space.
Its parameters are:
degree: the highest interaction order. Higher degrees give more flexible boundaries and more risk of overfitting.coef0: the constant term. It controls how much lower-degree terms matter relative to higher-degree terms.gamma: a scale on the dot product.
The kernel values can grow very large or shrink toward zero as the degree rises, which makes optimization numerically harder. Scaling the inputs helps. In practice, degrees of 2 or 3 are common, and higher degrees are rarely better than the RBF kernel.
The RBF kernel
The radial basis function (Gaussian) kernel is:
K(x, z) = exp(-gamma * ||x - z||^2)
Its value is 1 when the points coincide and decays toward 0 as they move apart. Its implicit feature space is infinite-dimensional, so it can fit very flexible boundaries. Each support vector contributes a bump of influence around itself, and the decision function is a weighted sum of those bumps.
Two parameters control the fit:
C: the cost of margin violations, as before.gamma: the inverse of the kernel's reach. Large gamma gives narrow bumps and a wiggly boundary that can memorize training points. Small gamma gives wide bumps and a smoother boundary that approaches a linear one.
Scikit-learn's default gamma="scale" uses 1 / (n_features * X.var()), which adapts to the data's spread.
Comparing the three on one dataset
The following script fits each kernel on the two-moons dataset, a problem that is not linearly separable, and reports cross-validated accuracy. Scaling sits inside the pipeline so each fold fits the scaler on its own training part.
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)
models = {
"linear": SVC(kernel="linear", C=1.0),
"poly deg 3": SVC(kernel="poly", degree=3, coef0=1.0, C=1.0),
"rbf": SVC(kernel="rbf", gamma="scale", C=1.0),
}
for name, svc in models.items():
pipe = make_pipeline(StandardScaler(), svc)
scores = cross_val_score(pipe, X, y, cv=5)
print(f"{name:12s} mean accuracy = {scores.mean():.3f}")Expect the linear kernel to trail the other two, because a straight line cannot separate interleaved crescents. The polynomial and RBF kernels should both do well here. The exact numbers depend on the library version, so treat the ordering as the lesson, not the digits.
How the kernels differ
| Property | Linear | Polynomial | RBF |
|---|---|---|---|
| Boundary shape | Hyperplane | Smooth, global curves | Local, arbitrarily flexible |
| Parameters | C | C, degree, coef0, gamma | C, gamma |
| Feature space | Original | Finite (all products up to degree) | Infinite-dimensional |
| Interpretable weights | Yes | Hard | No |
| Typical use | Many features, large data | Known interaction structure | General-purpose default |
| Training cost | Lowest | Moderate | Moderate to high |
Choosing in practice
- Scale the features first. Every kernel except the linear one depends on distances or products, so one large-valued feature can dominate. Even linear SVMs converge faster and regularize more evenly after scaling.
- Start with the linear kernel as a baseline. It is fast, and its score tells you how much nonlinearity the problem has.
- Try RBF next. It needs only C and gamma, and it handles most nonlinear problems.
- Try polynomial when domain knowledge suggests interactions of a known order, such as pairwise feature products.
- Compare candidates by cross-validation on the training data, and report the final score on a held-out test set.
A useful rule of thumb: when the number of features is much larger than the number of samples, the linear kernel is usually enough. When features are few and samples are many, RBF has room to help but training time grows quickly with the sample count.
Common errors
- Skipping scaling. An RBF SVM on unscaled data treats the largest-range feature as nearly the only one.
- Tuning only C. With RBF, C and gamma interact. A large gamma with a large C overfits badly, and a tiny gamma with a tiny C underfits. Tune them together on a log-spaced grid.
- Using a high polynomial degree. Fits get unstable, and the training time rises. Start at 2 or 3.
- Picking the kernel on the test set. Repeatedly checking test accuracy leaks information. Use cross-validation for selection.
- Using
SVC(kernel="linear")on huge data. Its training time grows between quadratically and cubically with samples. UseLinearSVCinstead.
Exercise
You have 500 samples and 20,000 TF-IDF text features, and a linear SVM already scores 0.93 in cross-validation. A colleague suggests an RBF SVM with a grid search over C and gamma. What do you recommend, and why?
Show answer
Keep the linear kernel, and tune only C. With far more features than samples, the data is high-dimensional and often close to linearly separable, so an RBF kernel adds little flexibility but adds a second parameter, more tuning time, and more overfitting risk. You may still run RBF as a cross-validated comparison. Switch only if it beats the linear score by a margin larger than the fold-to-fold variation.
Exercise
An RBF SVM reaches 100% training accuracy but 70% validation accuracy. Which direction should you move gamma and C, and why?
Show answer
Lower gamma and probably lower C. A high training score with a large gap to validation means overfitting. Smaller gamma widens each support vector's influence and smooths the boundary. Smaller C allows more margin violations and a simpler boundary. Confirm the change with a cross-validated grid search rather than adjusting by hand.