3.3 Support Vector Machines
3.3 Support Vector Machines
Key Concepts
3.3.1 Maximum Margin Classifier
SVMs find the hyperplane that maximizes the margin between classes.
Linear Separability
Linearly separable data:
Class +1: ● ● ●
● ● Many possible
● separating lines
───────────────────────── exist
Class -1: ○ ○
○ ○ ○
○ ○ The Margin
●
● ●
● ●
●
─────────────────────── w·x + b = 1 (positive margin)
↑
│ margin = 2/||w||
↓
═══════════════════════ w·x + b = 0 (decision boundary)
↑
│ margin = 2/||w||
↓
─────────────────────── w·x + b = -1 (negative margin)
○
○ ○
○ ○
○ ○Key insight: Maximizing margin = minimizing ||w||
Mathematical Formulation
Decision function:
f(x) = sign(w · x + b)
Where:
- w = weight vector (normal to hyperplane)
- b = bias (offset from origin)
- w · x + b = 0 defines the hyperplaneOptimization problem:
Maximize: margin = 2 / ||w||
Subject to: y_i(w · x_i + b) >= 1 for all i
Equivalent to:
Minimize: (1/2) ||w||^2
Subject to: y_i(w · x_i + b) >= 1 for all iSupport Vectors
Points exactly on the margin boundaries:
y_i(w · x_i + b) = 1
These are the SUPPORT VECTORS:
- Only these points determine the hyperplane
- Removing non-support vectors doesn't change the solution
- Typically a small subset of training data
●
● <- support vector
───────●─────────────────
═══════════════════════════
───────○─────────────────
○ <- support vector
○3.3.2 Soft Margin SVM
Real data is rarely perfectly separable. Allow some misclassifications.
Slack Variables
Introduce ξ_i >= 0 for each sample:
y_i(w · x_i + b) >= 1 - ξ_i
ξ_i = 0: correctly classified, outside margin
0 < ξ_i < 1: correctly classified, inside margin
ξ_i = 1: on decision boundary
ξ_i > 1: misclassifiedVisualization:
●
● ●
● ● ξ = 0 (correct, outside margin)
─────●───────────────────── margin
↓ ● ξ = 0.3 (correct, inside margin)
═══════════════════════════ decision boundary
○ ξ = 1.5 (misclassified!)
─────○───────────────────── margin
○ ○
○ ○Soft Margin Optimization
Minimize: (1/2) ||w||^2 + C * sum(ξ_i)
Subject to: y_i(w · x_i + b) >= 1 - ξ_i
ξ_i >= 0
Where C = regularization parameterEffect of C:
Large C: Penalize misclassifications heavily
-> Smaller margin, fewer errors
-> Risk of overfitting
Small C: Allow more misclassifications
-> Larger margin, more errors
-> More regularization
C -> ∞: Hard margin (no slack)
C -> 0: Ignore data, maximum marginHigh C (C=1000): Low C (C=0.1):
● ●
● ● ● ●
● ● ● ●
──────────────── ────────────────
═══════════════ ═══════════════════
──────○───────── ────────────────
○ ○ ○ ○
○ ○ ○ ○
○ ○
Tight fit, complex boundary Wide margin, simpler boundary3.3.3 Dual Formulation
The SVM optimization can be reformulated using Lagrange multipliers.
Primal vs Dual
Primal (original):
Minimize: (1/2) ||w||^2 + C * sum(ξ_i)
Variables: w, b, ξ (d + 1 + n variables)Dual (Lagrangian):
Maximize: sum(α_i) - (1/2) sum_i sum_j (α_i α_j y_i y_j x_i · x_j)
Subject to: 0 <= α_i <= C
sum(α_i y_i) = 0
Variables: α (n variables, one per sample)Why Dual Matters
-
Depends only on dot products x_i · x_j
- Enables the kernel trick!
-
Sparsity in α
- Most α_i = 0 (non-support vectors)
- Only support vectors have α_i > 0
-
Complexity depends on n, not d
- Better when d >> n
Solution from Dual
w = sum(α_i y_i x_i) (weighted sum of support vectors)
b = y_j - sum(α_i y_i x_i · x_j) for any support vector j
Prediction:
f(x) = sign(sum(α_i y_i x_i · x) + b)
= sign(sum(α_i y_i K(x_i, x)) + b) (with kernels)3.3.4 The Kernel Trick
Map data to higher dimensions where it becomes linearly separable.
The Problem
Not linearly separable in 2D:
○ ○ ○
○ ● ● ● ○
○ ● ● ● ○
○ ● ● ● ○
○ ○ ○
No line can separate ● from ○Feature Mapping
Map to higher dimension:
φ: R^d -> R^D (D >> d)
Example: φ(x1, x2) = (x1, x2, x1^2 + x2^2)
In 3D, the classes become separable by a plane!The Trick
Computing φ(x) explicitly is expensive for high D.
Key insight: SVM only needs dot products φ(x_i) · φ(x_j)
Kernel function:
K(x_i, x_j) = φ(x_i) · φ(x_j)
Compute the dot product in high-D space
WITHOUT explicitly computing φ!Common Kernels
Linear Kernel:
K(x, z) = x · z
No mapping, equivalent to linear SVM
Use when: data is linearly separable, high-d sparse dataPolynomial Kernel:
K(x, z) = (x · z + c)^d
Maps to polynomial feature space
Parameters: degree d, constant c
Example (d=2, c=1):
K(x, z) = (x · z + 1)^2
Implicitly computes: (1, √2·x1, √2·x2, x1^2, x2^2, √2·x1·x2)RBF (Radial Basis Function) / Gaussian Kernel:
K(x, z) = exp(-γ ||x - z||^2)
= exp(-||x - z||^2 / (2σ^2))
Maps to INFINITE dimensional space!
Parameters: γ (or σ)
γ large: Each point has local influence (complex boundary)
γ small: Points have wide influence (smooth boundary)Sigmoid Kernel:
K(x, z) = tanh(α · x · z + c)
Similar to neural network activation
Not always valid (not positive semi-definite for all α, c)Kernel Comparison
| Kernel | Parameters | Implicit Dimension | Use Case |
|---|---|---|---|
| Linear | None | d | Linearly separable, text |
| Polynomial | degree, c | O(d^degree) | Known polynomial relationship |
| RBF | γ | Infinite | Default choice, complex boundaries |
| Sigmoid | α, c | - | Neural network-like |
RBF Kernel Intuition
γ = 0.1 (small): γ = 10 (large):
Smooth, wide influence Sharp, local influence
●●● ●●●
●●●●● ●●●●●
●●●●●●● ●●●●●●●
─────────── ─┐ ┌─┐ ┌─
○○○○○○○○○○○ ○○│●│○│●│○○
└─┘ └─┘
Underfitting risk Overfitting risk3.3.5 SVM for Regression (SVR)
Adapt SVM for continuous targets using ε-insensitive loss.
ε-Insensitive Tube
●
● ●
───────────────────── y = f(x) + ε
═══════════════════════ y = f(x) (prediction)
───────────────────── y = f(x) - ε
●
●
Points inside tube: no penalty
Points outside tube: linear penaltySVR Optimization
Minimize: (1/2) ||w||^2 + C * sum(ξ_i + ξ_i*)
Subject to: y_i - (w · x_i + b) <= ε + ξ_i
(w · x_i + b) - y_i <= ε + ξ_i*
ξ_i, ξ_i* >= 0
Where:
- ε = tube width (tolerance)
- ξ_i, ξ_i* = slack for above/below tube3.3.6 Multi-class SVM
SVMs are inherently binary. Extend to multi-class:
One-vs-Rest (OvR)
K classes -> K binary classifiers
Classifier 1: Class 1 vs {2, 3, ..., K}
Classifier 2: Class 2 vs {1, 3, ..., K}
...
Classifier K: Class K vs {1, 2, ..., K-1}
Prediction: class with highest scoreOne-vs-One (OvO)
K classes -> K(K-1)/2 binary classifiers
All pairs: (1,2), (1,3), ..., (K-1, K)
Prediction: majority vote across all classifiersComparison:
| Method | # Classifiers | Training | Prediction |
|---|---|---|---|
| OvR | K | Imbalanced classes | Fast |
| OvO | K(K-1)/2 | Smaller datasets | Slower |
3.3.7 SVM Hyperparameters
Key Parameters
| Parameter | Effect | Tuning |
|---|---|---|
| C | Regularization strength | Higher = less regularization |
| kernel | Feature mapping | Try RBF first |
| γ (RBF) | Kernel bandwidth | Higher = more complex |
| degree (poly) | Polynomial degree | Start with 2-3 |
Tuning Strategy
from sklearn.model_selection import GridSearchCV
from sklearn.svm import SVC
param_grid = {
'C': [0.1, 1, 10, 100],
'gamma': [0.001, 0.01, 0.1, 1],
'kernel': ['rbf', 'linear']
}
grid = GridSearchCV(SVC(), param_grid, cv=5)
grid.fit(X_train, y_train)C and γ Interaction (RBF)
Low γ High γ
┌─────────────────┬─────────────────┐
│ │ │
Low C │ Underfitting │ Underfitting │
│ (too smooth) │ (regularized) │
│ │ │
├─────────────────┼─────────────────┤
│ │ │
High C │ Good fit │ Overfitting │
│ (smooth) │ (too complex) │
│ │ │
└─────────────────┴─────────────────┘3.3.8 Computational Complexity
Training
General SVM: O(n^2) to O(n^3) depending on solver
- Quadratic programming with n constraints
- SMO algorithm: O(n^2) typical case
Linear SVM (liblinear): O(n * d)
- Much faster for linear kernelPrediction
Kernel SVM: O(n_sv * d) per sample
- n_sv = number of support vectors
- Can be slow if many support vectors
Linear SVM: O(d) per sample
- Just compute w · x + bMemory
Kernel SVM: O(n^2) for kernel matrix
Linear SVM: O(n * d) for dataQuestions & Answers
⭐ Q1: How do SVMs work? What is the kernel trick?
Answer:
How SVMs Work:
SVMs find the optimal hyperplane that separates classes with maximum margin.
1. Find hyperplane: w · x + b = 0
2. Maximize margin: distance between closest points of each class
3. Margin = 2/||w||, so minimize ||w||^2
4. Support vectors: points on the margin boundaryOptimization:
Minimize: (1/2) ||w||^2 + C * sum(ξ_i)
Subject to: y_i(w · x_i + b) >= 1 - ξ_i
- C controls trade-off between margin and errors
- ξ_i allows soft margin (some misclassifications)The Kernel Trick:
When data isn't linearly separable, map to higher dimensions.
Problem: Computing φ(x) in high-D is expensive
Solution: Kernel function K(x, z) = φ(x) · φ(z)
Key insight: SVM only needs dot products, not explicit φCommon Kernels:
Linear: K(x, z) = x · z
Polynomial: K(x, z) = (x · z + c)^d
RBF: K(x, z) = exp(-γ ||x - z||^2)RBF Kernel:
- Maps to infinite dimensions
- Most flexible, default choice
- γ controls complexity (high γ = complex boundary)
Why it's powerful:
- Compute infinite-dimensional dot products in O(d) time
- Find non-linear boundaries efficiently
- Only need to store support vectors
⭐ Q2: When would you use SVM over logistic regression?
Answer:
Use SVM when:
1. Clear margin of separation exists
- SVM maximizes margin explicitly
- Better generalization when classes are well-separated
2. High-dimensional data (d >> n)
- SVM with linear kernel works well
- Text classification, genomics
3. Need non-linear boundaries
- Kernel trick handles complex patterns
- RBF kernel very flexible
4. Outliers are a concern
- Soft margin handles outliers
- Only support vectors affect decision boundary
5. Don't need probability outputs
- SVM gives hard classifications
- (Can use Platt scaling for probabilities, but adds complexity)Use Logistic Regression when:
1. Need probability estimates
- LR outputs calibrated probabilities directly
- Important for ranking, thresholding
2. Interpretability matters
- Coefficients have clear meaning (log-odds)
- Feature importance is straightforward
3. Large datasets
- LR scales better: O(n*d) vs O(n^2) for kernel SVM
- Online learning possible
4. Multi-class is natural
- Softmax extends naturally
- SVM needs OvR or OvO
5. Updating model frequently
- LR easier to update incrementally
- SVM needs retrainingComparison Table:
| Aspect | SVM | Logistic Regression |
|---|---|---|
| Output | Class label | Probability |
| Non-linear | Kernel trick | Feature engineering |
| Scalability | O(n^2) kernel | O(n*d) |
| Interpretability | Low (kernel) | High |
| Outlier handling | Good (margin) | Sensitive |
| Sparse data | Excellent | Good |
Practical Advice:
- Start with logistic regression (simpler, faster)
- Try SVM if LR underperforms
- For text/high-d sparse: linear SVM often best
- For complex boundaries: RBF SVM or neural networksQ3: Explain the role of C in SVM.
Answer:
C is the regularization parameter controlling the trade-off between margin size and classification errors.
Mathematical Role:
Minimize: (1/2) ||w||^2 + C * sum(ξ_i)
└─────────────┘ └──────────┘
margin term error penaltyEffect of C:
Large C (e.g., 1000):
- Heavy penalty on errors
- Smaller margin, fewer misclassifications
- Fits training data closely
- Risk: OVERFITTING
Small C (e.g., 0.01):
- Light penalty on errors
- Larger margin, more misclassifications allowed
- Smoother decision boundary
- Risk: UNDERFITTINGVisual Intuition:
C = 0.1: C = 100:
Wide margin, some errors Narrow margin, few errors
● ● ● ●
● ● ● ●
──────────────── ──────●───────
○
════════════════ ════════════════
●
──────────────── ──────○───────
○ ○ ○ ○
○ ○ ○ ○
More regularization Less regularizationTuning C:
# Use cross-validation
C_values = [0.001, 0.01, 0.1, 1, 10, 100]
# Plot validation accuracy vs C
# Choose C with best validation performanceRelationship to Other Concepts:
- C = 1/λ where λ is regularization strength
- Similar to inverse of regularization in logistic regression
- C → ∞: hard margin SVM (no slack allowed)
Q4: What are support vectors and why are they important?
Answer:
Definition: Support vectors are the training points that lie exactly on the margin boundaries.
y_i(w · x_i + b) = 1 (equality, not inequality)Visualization:
●
●
● ● <- Support vector (on margin)
─────●─────────────────── margin boundary
═══════════════════════════ decision boundary
─────○─────────────────── margin boundary
○ ○ <- Support vector (on margin)
○
○
Only circled points are support vectorsWhy They're Important:
- Determine the solution:
w = sum(α_i y_i x_i) for support vectors only
The hyperplane depends ONLY on support vectors
Other points could be removed without changing the model- Sparsity:
Typically small fraction of data are support vectors
-> Efficient model (store only SVs)
-> Fast prediction (sum over SVs only)- Model complexity indicator:
Many support vectors -> complex boundary, possible overfitting
Few support vectors -> simple boundary, good generalization- Robustness:
Moving non-support vectors doesn't change the model
Only points near the boundary matterIn Soft Margin SVM:
Three types based on α_i:
- α_i = 0: Not a support vector (correctly classified, outside margin)
- 0 < α_i < C: On the margin (support vector)
- α_i = C: Inside margin or misclassified (bounded support vector)Q5: How does RBF kernel parameter γ affect the model?
Answer:
γ (gamma) controls the "reach" of each training example.
Mathematical Definition:
K(x, z) = exp(-γ ||x - z||^2)
γ = 1 / (2σ^2) where σ is the Gaussian widthEffect of γ:
Small γ (e.g., 0.01):
- Each point influences a WIDE area
- Smooth, simple decision boundary
- Risk: UNDERFITTING
Large γ (e.g., 100):
- Each point influences only NEARBY points
- Complex, wiggly decision boundary
- Risk: OVERFITTINGVisual Intuition:
γ = 0.1: γ = 10:
Smooth boundary Complex boundary
●●●● ●●●●
●●●●●● ●●●●●●
●●●●●●●● ●●●●●●●●
──────────── ─┐┌─┐┌─┐┌─
○○○○○○○○○○○○ ○○││○││○││○○
└┘ └┘ └┘
Wide Gaussian Narrow GaussianTuning γ:
# Common approach: grid search with C
param_grid = {
'C': [0.1, 1, 10, 100],
'gamma': ['scale', 'auto', 0.01, 0.1, 1]
}
# sklearn defaults:
# 'scale': 1 / (n_features * X.var())
# 'auto': 1 / n_featuresγ and C Interaction:
- High γ + High C: Very complex, overfitting
- High γ + Low C: Complex but regularized
- Low γ + High C: Smooth, may underfit
- Low γ + Low C: Very smooth, underfitting
Best: moderate γ, tune C via cross-validationInterview tip: Mention that γ = 'scale' (sklearn default) is often a good starting point, then tune with cross-validation.
Q6: What is the computational complexity of SVM?
Answer:
Training Complexity:
| SVM Type | Time | Space |
|---|---|---|
| Kernel SVM | O(n^2) to O(n^3) | O(n^2) |
| Linear SVM | O(n * d) | O(n * d) |
Kernel SVM Details:
- Must compute/store kernel matrix: O(n^2)
- QP solver: O(n^3) worst case
- SMO algorithm: O(n^2) typical
- Practical: works well up to ~10K-100K samplesLinear SVM (liblinear, SGD):
- No kernel matrix needed
- Coordinate descent: O(n * d * iterations)
- SGD: O(n * d) per epoch
- Scales to millions of samplesPrediction Complexity:
| SVM Type | Time per Sample |
|---|---|
| Kernel SVM | O(n_sv * d) |
| Linear SVM | O(d) |
Kernel SVM prediction:
f(x) = sum(α_i y_i K(x_i, x)) + b
= sum over n_sv support vectors
Linear SVM prediction:
f(x) = w · x + b
= single dot productPractical Implications:
Small data (n < 10K): Kernel SVM fine
Medium data (10K-100K): Consider linear SVM or approximations
Large data (> 100K): Use linear SVM, SGD, or kernel approximations
High-dimensional sparse (text):
- Linear SVM is often best
- Kernel SVM too slowKernel Approximations for Large Data:
- Nyström method: approximate kernel matrix
- Random Fourier Features: approximate RBF kernel
- Allows kernel-like flexibility with linear SVM speed