Angad Sandhu
Search
Browse
On this page

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 hyperplane

Optimization 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 i

Support 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:     misclassified

Visualization:

                ●
           ●    ●
      ●    ●         ξ = 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 parameter

Effect 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 margin
High C (C=1000):              Low C (C=0.1):
     ●                             ●
        ●  ●                          ●  ●
   ●       ●                     ●       ●
────────────────              ────────────────
═══════════════               ═══════════════════
──────○─────────              ────────────────
   ○       ○                     ○       ○
        ○  ○                          ○  ○
     ○                             ○

Tight fit, complex boundary    Wide margin, simpler boundary

3.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

  1. Depends only on dot products x_i · x_j

    • Enables the kernel trick!
  2. Sparsity in α

    • Most α_i = 0 (non-support vectors)
    • Only support vectors have α_i > 0
  3. 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 data

Polynomial 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

KernelParametersImplicit DimensionUse Case
LinearNonedLinearly separable, text
Polynomialdegree, cO(d^degree)Known polynomial relationship
RBFγInfiniteDefault 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 risk

3.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 penalty

SVR 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 tube

3.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 score

One-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 classifiers

Comparison:

Method# ClassifiersTrainingPrediction
OvRKImbalanced classesFast
OvOK(K-1)/2Smaller datasetsSlower

3.3.7 SVM Hyperparameters

Key Parameters

ParameterEffectTuning
CRegularization strengthHigher = less regularization
kernelFeature mappingTry RBF first
γ (RBF)Kernel bandwidthHigher = more complex
degree (poly)Polynomial degreeStart 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 kernel

Prediction

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 + b

Memory

Kernel SVM: O(n^2) for kernel matrix
Linear SVM: O(n * d) for data

Questions & 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 boundary

Optimization:

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 retraining

Comparison Table:

AspectSVMLogistic Regression
OutputClass labelProbability
Non-linearKernel trickFeature engineering
ScalabilityO(n^2) kernelO(n*d)
InterpretabilityLow (kernel)High
Outlier handlingGood (margin)Sensitive
Sparse dataExcellentGood

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 networks

Q3: 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 penalty

Effect 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: UNDERFITTING

Visual Intuition:

C = 0.1:                    C = 100:
Wide margin, some errors    Narrow margin, few errors

    ●  ●                        ●  ●
  ●      ●                    ●      ●
────────────────            ──────●───────
                              ○
════════════════            ════════════════
                              ●
────────────────            ──────○───────
  ○      ○                    ○      ○
    ○  ○                        ○  ○

More regularization         Less regularization

Tuning 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 performance

Relationship 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 vectors

Why They're Important:

  1. 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
  1. Sparsity:
Typically small fraction of data are support vectors
-> Efficient model (store only SVs)
-> Fast prediction (sum over SVs only)
  1. Model complexity indicator:
Many support vectors -> complex boundary, possible overfitting
Few support vectors -> simple boundary, good generalization
  1. Robustness:
Moving non-support vectors doesn't change the model
Only points near the boundary matter

In 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 width

Effect 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: OVERFITTING

Visual Intuition:

γ = 0.1:                      γ = 10:
Smooth boundary               Complex boundary

    ●●●●                          ●●●●
   ●●●●●●                        ●●●●●●
  ●●●●●●●●                      ●●●●●●●●
 ────────────                  ─┐┌─┐┌─┐┌─
○○○○○○○○○○○○                  ○○││○││○││○○
                                └┘ └┘ └┘

Wide Gaussian                 Narrow Gaussian

Tuning γ:

# 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-validation

Interview 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 TypeTimeSpace
Kernel SVMO(n^2) to O(n^3)O(n^2)
Linear SVMO(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 samples

Linear SVM (liblinear, SGD):

- No kernel matrix needed
- Coordinate descent: O(n * d * iterations)
- SGD: O(n * d) per epoch
- Scales to millions of samples

Prediction Complexity:

SVM TypeTime per Sample
Kernel SVMO(n_sv * d)
Linear SVMO(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 product

Practical 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 slow

Kernel Approximations for Large Data:

- Nyström method: approximate kernel matrix
- Random Fourier Features: approximate RBF kernel
- Allows kernel-like flexibility with linear SVM speed

Browse the library