A Support Vector Machine (SVM) is a supervised algorithm that finds the decision boundary (hyperplane) that maximizes the margin between classes.
Margin Maximization and Slack Variables
In linear classification, we find a hyperplane that separates classes.
Primal Optimization Problem (Soft Margin)
To allow for noise and misclassifications, we introduce slack variables . The objective minimizes:
subject to:
The parameter controls the trade-off: a small allows more margin violations (regularized), while a large forces a hard margin (sensitive to noise).
The Dual Formulation and the Kernel Trick
By reformulating the optimization problem using Lagrange multipliers, we express the decision function using inner products of training instances:
The coefficients are non-zero only for instances on the margin boundaries. These are the Support Vectors that determine the decision boundary.
The Kernel Trick
The kernel trick replaces the dot product with a kernel function , avoiding mapping data to high-dimensional spaces explicitly.
Polynomial Kernel:
Radial Basis Function (RBF) Kernel:
The parameter controls the RBF width: a larger makes the boundary narrower and more irregular, fitting specific instances.
Example: Non-Linear Kernel SVM
The following example demonstrates training an SVM with an RBF kernel:
Interactive Lab
import numpy as np
from sklearn.svm import SVC
# Non-linear XOR problem dataset
X = np.array([[0, 0], [1, 1], [1, 0], [0, 1]])
y = np.array([0, 0, 1, 1])
# Radial Basis Function (RBF) kernel SVM handles non-linear boundaries
clf = SVC(kernel='rbf', C=10.0, gamma=1.0)
clf.fit(X, y)
print(f"Predictions: {clf.predict(X)}")
print(f"Number of Support Vectors per class: {clf.n_support_}")
Expected output
Predictions: [0 0 1 1]
Number of Support Vectors per class: [2 2]
python
Interactive Lab
Train an RBF kernel SVM to solve the non-linear XOR problem. Inspect the support vectors selected by the model.
Step 1
Inspect the idea
Step 2
Edit the program
Step 3
Run and compare
Exercise
Test your understanding of SVM margin constraints:
Knowledge Check
What happens to the decision boundary if we increase the hyperparameter C to infinity?
Answer: The SVM behaves like a hard margin classifier, allowing zero margin violations but risking overfitting.
C acts as a penalty for margin violations. As C approaches infinity, violations are penalized infinitely, forcing the optimization to find a hard margin that perfectly separates all training data points.
What happens to the decision boundary if we increase the hyperparameter C to infinity?