Support Vector Machines
Searching for the separating boundary with the largest margin, and the kernel trick for non-linear boundaries.
The largest margin
For the classes \(y \in \{-1, +1\}\) we look for \(\mathbf{w}, b\) such that:
$$\min_{\mathbf{w}, b} \ \frac{1}{2}\|\mathbf{w}\|^2 \quad \text{s.t.} \quad y_i(\mathbf{w}^\top \mathbf{x}_i + b) \ge 1$$
The margin width equals \(2/\|\mathbf{w}\|\), so minimizing \(\|\mathbf{w}\|\) means maximizing the margin.
The soft margin
Real data is rarely perfectly separable, so we add slack variables \(\xi_i\):
$$\min \ \frac{1}{2}\|\mathbf{w}\|^2 + C\sum_i \xi_i$$
The parameter \(C\) balances the width of the margin against the number of errors allowed.
The kernel trick
The common RBF kernel:
$$K(\mathbf{x}, \mathbf{z}) = \exp\left(-\gamma \|\mathbf{x} – \mathbf{z}\|^2\right)$$
from sklearn.datasets import make_moons
from sklearn.model_selection import GridSearchCV
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.2, random_state=0)
pipe = make_pipeline(StandardScaler(), SVC(kernel="rbf"))
grid = GridSearchCV(pipe, {"svc__C": [0.1, 1, 10, 100],
"svc__gamma": [0.01, 0.1, 1, 10]}, cv=5)
grid.fit(X, y)
print(grid.best_params_, round(grid.best_score_, 3))Practical notes
- Always scale the features.
- Tune
Candgammatogether on a logarithmic grid. - The training time of a kernel SVC grows quickly with the number of examples; for very large data use
LinearSVCor other methods. - SVC does not give probabilities directly; the option
probability=Trueadds a costly internal calibration.
Lesson terms
- Support vectors
- The training points lying on or inside the margin, which determine the position of the decision boundary.
- Margin
- The distance between the decision boundary and the nearest training points of each class.
- The kernel trick
- Computing the inner product in a high-dimensional feature space directly through a kernel function, without carrying out the transformation explicitly.
Abstract
A support vector machine searches for a hyperplane that separates the two classes with the largest possible margin, determined by a few points close to the boundary called support vectors. The soft margin allows some errors and is controlled by the parameter C, and the kernel trick allows non-linear boundaries, such as the RBF kernel, without computing the transformation explicitly.
Review questions
-
What is the effect of increasing the parameter C?
A larger penalty on errors, so the margin becomes narrower and the model fits the training data more closely, with a risk of overfitting.
-
What is the role of gamma in the RBF kernel?
It determines the reach of each training point's influence; large values give more jagged boundaries.
Sources and references
Complete the lesson
You have completed all the lessons in the track! You can now request the track completion certificate.
Request the certificate