Quiz 2

Support Vector Machines

1939 words
10 min read
Python Week 1: the first filter for runtime behavior
Visual companion
Python
Type and operator map

Python Week 1: the first filter for runtime behavior

View
Revision summary

What this note is really saying

Short form

# Support Vector Machines ## 🎯 Learning Objectives - Explain how SVM finds the maximum margin hyperplane - Understand the role of support vectors - Use the kernel trick to handle non-linear data - Tune SVM hyperparameters (C, gamma, kernel) - Implement SVM for classification and regression ## 📋 Prerequisites - **L...

Support Vector Machines

🎯 Learning Objectives

  • Explain how SVM finds the maximum margin hyperplane
  • Understand the role of support vectors
  • Use the kernel trick to handle non-linear data
  • Tune SVM hyperparameters (C, gamma, kernel)
  • Implement SVM for classification and regression

📋 Prerequisites

  • Linear Algebra — hyperplanes, dot products, vector projections
  • Convex Optimization — understanding Lagrange multipliers (conceptual)
  • Logistic Regression — linear decision boundaries

📖 Core Content

8.1 Intuition: The Widest Possible Street

Imagine separating red and blue points with a line. Many lines work, but the best line is the one that's farthest from the nearest points on either side. SVM chooses the line that maximizes the "street" width between classes. (Diagram) The points closest to the boundary are support vectors — they "support" the margin. If they move, the boundary moves. Points far from the boundary don't matter at all. Key insight: Only the support vectors matter. The rest of the dataset can be ignored once the boundary is found. This makes SVM efficient even with large datasets.

8.2 Formal Definition

The Separating Hyperplane:
wTx+b=0w^T x + b = 0
Where ww is the normal vector (weights) and bb is the bias. Decision Function:
y^=sign(wTx+b)\hat{y} = \text{sign}(w^T x + b)
The Margin is the distance from the hyperplane to the nearest training example:
margin=2w\text{margin} = \frac{2}{\|w\|}
Hard Margin SVM (perfectly separable data):
Minimize 12w2 subject to y(i)(wTx(i)+b)1 for all i\text{Minimize } \frac{1}{2}\|w\|^2 \text{ subject to } y^{(i)}(w^T x^{(i)} + b) \geq 1 \text{ for all } i
This guarantees that:
  • All positive examples satisfy wTx+b1w^T x + b \geq 1
  • All negative examples satisfy wTx+b1w^T x + b \leq -1
  • No points fall inside the margin Soft Margin SVM (allows misclassifications):
Minimize 12w2+Ci=1mξi\text{Minimize } \frac{1}{2}\|w\|^2 + C\sum_{i=1}^{m} \xi_i
Where ξi0\xi_i \geq 0 are slack variables (penalty for each misclassified/within-margin point) and CC controls the tradeoff between margin width and violations.

8.3 Worked Example 1: Finding the Support Vectors

Consider three points: A(1,1, class +1), B(2,3, class -1), C(3,2, class -1). The optimal hyperplane is: w1+w2+b=0w_1 + w_2 + b = 0 (let's find it). For SVM, the support vectors satisfy y(i)(wTx(i)+b)=1y^{(i)}(w^T x^{(i)} + b) = 1. Using optimization (quadratic programming), we find: w=[2,2]w = [-2, -2], b=5b = 5 Hyperplane: 2x12x2+5=0-2x_1 - 2x_2 + 5 = 0, or x1+x2=2.5x_1 + x_2 = 2.5 Check margins:
  • A(1,1): 2(1)2(1)+5=1-2(1) -2(1) + 5 = 1 → on the margin boundary ✓
  • B(2,3): 2(2)2(3)+5=5-2(2) -2(3) + 5 = -5 → far from boundary ✓
  • C(3,2): 2(3)2(2)+5=5-2(3) -2(2) + 5 = -5 → far from boundary ✓ Support vectors: Only A is a support vector! B and C don't influence the boundary.

8.4 The Kernel Trick

For non-linear data, SVM can't find a separating hyperplane in the original space. The kernel trick implicitly maps data to a higher-dimensional space where it becomes linearly separable — without ever computing the transformation.
K(x,x)=ϕ(x)Tϕ(x)K(x, x') = \phi(x)^T \phi(x')
Common Kernels:
KernelFormulaWhen to Use
LinearxTxx^T x'Data is linearly separable
Polynomial(γxTx+r)d(\gamma x^T x' + r)^dModerate non-linearity
RBF (Gaussian)$\exp(-\gamma \x - x'\
Sigmoidtanh(γxTx+r)\tanh(\gamma x^T x' + r)Neural network-like
python
# runnable
import numpy as np
import matplotlib.pyplot as plt
from sklearn.svm import SVC
# Create non-linear data (concentric circles)
np.random.seed(42)
X = np.random.randn(200, 2)
y = (X[:, 0]**2 + X[:, 1]**2 > 1.5).astype(int)
# SVM with RBF kernel
svm = SVC(kernel='rbf', C=10, gamma=1.0)
svm.fit(X, y)
print(f"Accuracy: {svm.score(X, y):.3f}")
print(f"Number of support vectors: {len(svm.support_)}")
# Plot decision boundary
xx, yy = np.meshgrid(np.linspace(-3, 3, 50), np.linspace(-3, 3, 50))
Z = svm.decision_function(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
plt.contourf(xx, yy, Z, levels=20, cmap='RdBu', alpha=0.7)
plt.scatter(X[y==0,0], X[y==0,1], color='blue', label='Class 0')
plt.scatter(X[y==1,0], X[y==1,1], color='red', label='Class 1')
plt.scatter(svm.support_vectors_[:,0], svm.support_vectors_[:,1],
            s=100, facecolors='none', edgecolors='k', label='Support Vectors')
plt.legend()
plt.grid(True)
plt.show()

8.5 Hyperparameter Tuning

C (Regularization parameter):
  • Small C: Large margin allowed, more training errors tolerated (high bias)
  • Large C: Small margin, few training errors tolerated (high variance) γ (Gamma - for RBF kernel):
  • Small γ: Large influence radius → smooth decision boundary (high bias)
  • Large γ: Small influence radius → wiggly boundary (high variance)
python
# runnable
from sklearn.svm import SVC
from sklearn.model_selection import GridSearchCV
from sklearn.datasets import load_iris
iris = load_iris()
X, y = iris.data, iris.target
param_grid = {
    'C': [0.1, 1, 10, 100],
    'gamma': [0.01, 0.1, 1, 'auto', 'scale'],
    'kernel': ['rbf']
}
grid = GridSearchCV(SVC(), param_grid, cv=5, scoring='accuracy', n_jobs=-1)
grid.fit(X, y)
print(f"Best params: {grid.best_params_}")
print(f"Best CV accuracy: {grid.best_score_:.3f}")

8.6 SVM for Regression (SVR)

SVM can also predict continuous values. Instead of maximizing the margin between classes, SVR finds a tube around the regression line with width ε. Points inside the tube cost nothing; points outside are penalized.
Minimize 12w2+Ci=1mmax(0,y(i)(wTx(i)+b)ϵ)\text{Minimize } \frac{1}{2}\|w\|^2 + C\sum_{i=1}^{m} \max(0, |y^{(i)} - (w^T x^{(i)} + b)| - \epsilon)

8.7 When to Use / Not Use

When to UseWhen NOT to Use
Medium-sized datasets (< 100k rows)Very large datasets (scales O(m²) to O(m³))
Clear margin separationOverlapping classes with much noise
High-dimensional data (p > m)Need probability estimates (SVM gives poor calibration)
Text classification (works great)Need interpretability (black box with kernels)
Non-linear data with RBF kernelMany features (n > 100k)

📐 Key Formulas / Concepts

ConceptFormulaNotes
HyperplanewTx+b=0w^T x + b = 0Decision boundary
Margin$\frac{2}{\w\
Hard SVM Objective$\min \frac{1}{2}\w\
Soft SVM Objective$\min \frac{1}{2}\w\
RBF Kernel$\exp(-\gamma\x-x'\
Decision functionf(x)=αiy(i)K(x(i),x)+bf(x) = \sum \alpha_i y^{(i)} K(x^{(i)}, x) + bOnly support vectors matter

⚠️ Common Pitfalls

Pitfall 1: Not Scaling Features

The mistake: Using raw features with SVM. Why: SVM is distance-based — the margin is measured in feature space. Features with large ranges dominate. Fix: Standardize all features to mean 0, std 1. This is essential for SVM.

Pitfall 2: Choosing Wrong C Value

The mistake: Using default C=1.0 without tuning. Why: C controls the bias-variance tradeoff. Too high C overfits (tight margin), too low C underfits (large margin). Fix: Search C across [0.001, 0.01, 0.1, 1, 10, 100] using cross-validation.

Pitfall 3: Using Linear Kernel on Non-Linear Data

The mistake: Linear kernel on data with circular or intricate class boundaries. Why: Linear SVM can't separate non-linear data. Fix: Start with RBF kernel — it's the most flexible. Tune gamma to control complexity.

📝 Practice Questions

Q1: What makes a point a "support vector"?
A point x(i)x^{(i)} is a support vector if it lies on the margin boundary or inside the margin. Mathematically: y(i)(wTx(i)+b)1y^{(i)}(w^T x^{(i)} + b) \leq 1. Support vectors are the only points that determine the SVM's decision boundary — removing any non-support vector doesn't change the model. Q2: How does the C parameter affect SVM?
C controls penalty for margin violations:
  • C large (e.g., 100): Heavy penalty for misclassifications → narrower margin, fewer support vectors, may overfit
  • C small (e.g., 0.01): Light penalty → wider margin, more support vectors, may underfit
C is inversely related to regularization strength (like 1/α in ridge regression). Q3: What is the kernel trick and why is it useful?
The kernel trick computes dot products in a transformed feature space without explicitly computing the transformation φ(x)φ(x). This:
  1. Saves computation (mapping to infinite dimensions would be impossible)
  2. Allows SVM to find non-linear decision boundaries efficiently
  3. Works because SVM only needs dot products, not the transformed coordinates themselves Q4: For an RBF kernel, what does gamma control?
Gamma (γγ) controls the influence radius of each training example:
  • Small γ: Each example influences a large area → smooth boundary (high bias)
  • Large γ: Each example has tiny influence → wiggly boundary (high variance)
Default: γ = 1/(n_features × variance(X)) or just 1/n_features. Q5: Why is SVM sensitive to feature scaling?
The margin is measured in feature space — it's the perpendicular distance from the hyperplane to the nearest points. If one feature has range [0, 1000] and another [0, 1], the first feature dominates distance calculations. The margin will be defined almost entirely by that feature.
Solution: Standardize all features to have zero mean and unit variance. Q6: Compute w\|w\| if the margin width is 2.
Margin =2/w=2    w=1= 2/\|w\| = 2 \implies \|w\| = 1
The norm of w is inversely proportional to the margin. To maximize the margin, we minimize w\|w\|. Q7: Your SVM takes too long to train on 100k examples. What do you do?
SVM training is O(m²) to O(m³) for RBF kernel. Options:
  1. Use LinearSVC (linear kernel, O(m) training) — much faster
  2. Reduce dataset size (random subset)
  3. Use SGDClassifier with hinge loss (online SVM approximation)
  4. Use a different model (Random Forest scales better)
SVM is best for small-to-medium datasets (< 10k is ideal). Q8: Implement SVM with polynomial kernel.
python
from sklearn.svm import SVC
from sklearn.datasets import make_moons
from sklearn.model_selection import train_test_split

X, y = make_moons(n_samples=200, noise=0.15, random_state=42)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

svm = SVC(kernel='poly', degree=3, C=10, gamma='auto')
svm.fit(X_train, y_train)
print(f"Accuracy: {svm.score(X_test, y_test):.3f}")
Q9: What is the dual formulation of SVM?
The dual formulation expresses SVM optimization in terms of Lagrange multipliers αiα_i: maxααi12αiαjyiyjK(xi,xj)\max_α \sum α_i - \frac{1}{2}\sum\sum α_i α_j y_i y_j K(x_i, x_j)
Subject to 0αiC0 \leq α_i \leq C and αiyi=0\sum α_i y_i = 0.
The dual is important because:
  1. It introduces the kernel trick naturally
  2. Most αi=0α_i = 0 — only support vectors have αi>0α_i > 0
  3. The decision function becomes: f(x)=αiyiK(xi,x)+bf(x) = \sum α_i y_i K(x_i, x) + b Q10: When would you choose SVM over Random Forest?
Choose SVM over RF when:
  1. Data is well-structured with clear margin (text, images with good features)
  2. n_features > m_samples (high-dim, low-sample — SVM excels)
  3. You need a compact model (only support vectors stored)
  4. Binary classification with interpretable margin
Choose RF when:
  1. Data is large (> 10k examples)
  2. Feature types are mixed
  3. You want feature importance rankings
  4. Training speed matters Q11: How does the ε parameter work in SVR?
ε-insensitive loss: points with error yy^<ε|y - ŷ| < ε cost nothing (they're "inside the tube"). Points outside the tube are penalized linearly: L(y,y^)=max(0,yy^ε)L(y, ŷ) = \max(0, |y - ŷ| - ε)
Small ε: tight tube, more support vectors, may overfit. Large ε: loose tube, simpler model. Q12: Your SVM gives poor probability estimates. Why?
SVM is not designed for probability estimation — it outputs distance to the hyperplane, not a probability. sklearn's probability=True uses Platt scaling (fitting a logistic regression on SVM outputs), but:
  1. It requires extra cross-validation (slower)
  2. Calibration may be poor, especially with small data
  3. Probabilities don't represent true class probabilities
Use logistic regression or calibrated Random Forest if probabilities are critical.

🔗 Cross-References

Document outline

Keep your place and jump directly to a heading.

Table of Contents
System Normal // Awaiting Context

Intelligence Hub

Navigate the knowledge graph to generate context. The Hub adapts dynamically to surface backlinks, related notes, and metadata insights.