SVM Kernels
Press Next → or use ← → arrow keys
What Is A Kernel, And Why Do We Need One?
Now imagine gently pushing the red dots upward based on how close they sit to the middle. Suddenly you have a 3D scene: reds float high, blues stay flat. A horizontal card can slice cleanly between them. That upward push is what a kernel does — invisibly, and without ever actually moving the points.
A kernel function K(a, b) measures how similar two data points are, as if they had been lifted into a much richer feature space — without ever computing the coordinates in that space. This trick lets a linear SVM discover curved, circular, or wave-shaped decision boundaries at the cost of a plain dot product.
The Kernel Trick — Visualised
SVM training and prediction only ever need dot products between pairs of points. A kernel function computes that dot product as if the points had already been lifted — no coordinates in the lifted space are ever built. You get non-linear boundaries at the cost of a simple similarity calculation.
The Four Kernels You'll Actually Use
Linear for text · RBF for the unknown · Polynomial when features interact meaningfully · Sigmoid almost never — reach for a neural network instead.
Decision Boundaries — Same Data, Four Kernels
If your two classes are separated by a curve, don't ask a linear kernel to draw a line through them — you'll get ~50% accuracy. Look at a scatter of your data first. If a straight line would work, use Linear. Otherwise start with RBF — it handles almost anything.
γ On RBF — The Reach Of Each Point's Influence
The gamma (γ) parameter in RBF controls how far each support vector's influence spreads. Think of each point holding a torch — high γ is a narrow beam, low γ is a floodlight.
sklearn's gamma='scale' auto-adapts to feature variance —
it's the right starting point on almost every dataset. Only override with a specific value
when you're actively grid-searching. Never leave γ at the legacy 'auto'.
C — Wide Margin Or Tight Fit?
| C range | Margin | Training accuracy | Risk |
|---|---|---|---|
| 0.001 – 0.1 | Very wide | Low | Underfits |
| 0.5 – 5 | Balanced | Medium | Good default |
| 10 – 100 | Narrow | High | Watch overfitting |
| 1000+ | Razor-thin | Very high | Severe overfitting |
Tune C And γ Together — The GridSearch Heatmap
The two knobs interact. High-C-with-high-γ is a disaster (memorises everything). Low-C-with-low-γ is another (underfits). Sweep both on a log grid and let CV find the sweet spot.
When you have three or more hyperparameters, RandomizedSearchCV with
loguniform distributions finds better regions faster than a full grid.
For plain (C, γ) tuning, either works — but never use linear spacing (range(1, 100)).
Always log spacing: np.logspace(-3, 3, 7).
Which Kernel Should I Use?
RBF is the safest first choice for anything that isn't obviously text or graph-shaped. Fit an RBF SVM with default parameters, look at the CV score. If it's decent, tune C and γ. If it's poor, try Linear (for high-dim) or Polynomial (if interactions might matter).
Feature Scaling — Non-Negotiable For Non-Linear Kernels
StandardScaler puts every feature on the same footing (mean 0, std 1) so γ can act fairly on all of them. Skip scaling, and γ becomes meaningless.
Wrap StandardScaler and SVC inside a Pipeline so that
cross-validation refits the scaler on each fold's training partition. Fit the scaler on train + test
combined, and you leak test statistics into training — inflating every CV score by 2–5%.
Implementation — Sklearn, Pipeline & Grid Search
from sklearn.svm import SVC, LinearSVC from sklearn.preprocessing import StandardScaler from sklearn.pipeline import Pipeline from sklearn.model_selection import GridSearchCV, RandomizedSearchCV from scipy.stats import loguniform import numpy as np # ── RBF default · always inside a pipeline ───────────── rbf = Pipeline([ ('scaler', StandardScaler()), ('clf', SVC(kernel='rbf', C=1.0, gamma='scale', probability=True)), ]) rbf.fit(X_train, y_train) # ── GridSearchCV · log-spaced C and γ ───────────────── grid = GridSearchCV(rbf, param_grid={ 'clf__C': np.logspace(-2, 2, 5), 'clf__gamma': np.logspace(-4, 1, 6), }, cv=5, scoring='roc_auc', n_jobs=-1).fit(X_train, y_train) print(grid.best_params_) # ── RandomizedSearchCV · better with ≥3 params ──────── rand = RandomizedSearchCV(rbf, param_distributions={ 'clf__C': loguniform(1e-2, 1e2), 'clf__gamma': loguniform(1e-4, 1e1), }, n_iter=40, cv=5, scoring='roc_auc', n_jobs=-1).fit(X_train, y_train) # ── Text · LinearSVC scales to millions of features ── text = Pipeline([ ('tfidf', TfidfVectorizer(ngram_range=(1, 2))), ('clf', LinearSVC(C=1.0, max_iter=5000)), ]).fit(docs, labels) # ── Polynomial · watch degree ──────────────────────── poly = Pipeline([ ('scaler', StandardScaler()), ('clf', SVC(kernel='poly', degree=3, coef0=1.0, C=1.0)), ])
Always wrap in a Pipeline so the scaler refits per CV fold.
Always use loguniform distributions for C and γ in random search — linear ranges
waste 90% of the budget in useless regions.
Kernel Cheat Sheet — Formula, Params, Use Cases
| Kernel | Formula | Key Params | Best For |
|---|---|---|---|
| Linear | aᵀ · b | C | Text · sparse · high-dim (LinearSVC scales to millions of features) |
| RBF (Gaussian) | exp(−γ‖a−b‖²) | C · γ | Default · non-linear boundaries of any shape |
| Polynomial | (γaᵀb + r)ᵈ | C · γ · degree · coef0 | Feature interactions · vision · NLP |
| Sigmoid | tanh(γaᵀb + r) | C · γ · coef0 | Rarely first choice · often use neural net instead |
| Precomputed | your K(a,b) | C | Custom similarity — graphs, strings, DNA, time series |
Common Pitfalls — What Silently Breaks SVM Kernels
StandardScaler, one large-scale feature dominates every kernel evaluation.range(1, 100) for C wastes 99% of the budget in useless regions. Always use np.logspace.Golden Rules — 1 to 3
StandardScaler and the SVM inside a Pipeline so cross-validation
refits per fold. Skipping this destroys the geometry every non-linear kernel depends on.
np.logspace(-3, 3, 7) for both. They interact — tuning one at a time gives you
the wrong optimum. Prefer RandomizedSearchCV with loguniform for larger searches.
Golden Rules — 4 to 6
precomputed kernel matrix.
✅ Scaler in Pipeline · ✅ Started with RBF · gamma='scale' · ✅ C & γ tuned jointly on log grid · ✅ Train / CV gap acceptable · ✅ Support-vector count under 50% · ✅ probability=True set at construction (if needed).
Kernels — The Magic That Curves A Linear Model
You now understand what a kernel is, how the trick avoids computing the lift explicitly, how the four sklearn kernels differ in the boundaries they produce, how C and γ steer the bias-variance balance, and how to search for the right pair. Every kernel SVM you tune from now on rests on exactly these ideas.
Study Kernel PCA (the same trick for dimensionality reduction) and Gaussian Processes (Bayesian cousin of RBF-SVM). For scale, learn Nyström approximation and SGDClassifier(loss='hinge'). Practise on Iris, MNIST, and Breast Cancer — RBF wins on all three with the right C and γ.
✨ End of tutorial · Press ← to review, or click Restart