Support Vector Machines & The Kernel Trick

Derive geometric margins, the primal and dual quadratic programs, KKT complementary slackness, the Mercer kernel condition, and zero-dependency implementations in Python and Rust.

01. Supervised Machine Learning Engineering9 min read

Support Vector Machines (SVMs) represent one of the most mathematically rigorous algorithms in statistical learning theory. Grounded in Vapnik-Chervonenkis (VC) Dimension bounds, SVMs seek the unique decision boundary that maximizes the geometric margin separating two classes, minimizing structural risk rather than empirical risk alone.

Geometric SeparationGeometry
2 / ||w||

The optimal separating hyperplane maximizes the margin width while maintaining strict constraint boundaries.

1. Geometric Margin and Primal Formulation#

Consider a linearly separable binary dataset (x1,y1),…,(xN,yN)(x_1, y_1), \dots, (x_N, y_N) with feature vectors xi∈Rdx_i \in \mathbb{R}^d and binary polar labels yi∈{−1,+1}y_i \in \{-1, +1\}.

A separating affine hyperplane is defined by:

{x∈Rd:wTx+b=0}\{x \in \mathbb{R}^d : w^T x + b = 0\}
Architecture Diagram
Rendering diagram...

Derivation of the Margin Width#

Let x0x_0 be any point in space. The signed Euclidean distance γ\gamma from x0x_0 to the hyperplane is computed by orthogonal projection along unit normal vector w∥w∥2\frac{w}{\|w\|_2}:

γ=wTx0+b∥w∥2\gamma = \frac{w^T x_0 + b}{\|w\|_2}

For classified samples with labels yi∈{−1,+1}y_i \in \{-1, +1\}, the geometric margin is:

γi=yi(wTxi+b∥w∥2)\gamma_i = y_i \left( \frac{w^T x_i + b}{\|w\|_2} \right)
1

Step 1: Maximize the Minimum Margin

We seek parameters (w,b)(w, b) that maximize the distance to the closest training sample:

max⁡w,bmin⁡i=1,…,Nyi(wTxi+b∥w∥2)\max_{w, b} \min_{i=1,\dots,N} y_i \left( \frac{w^T x_i + b}{\|w\|_2} \right)
2

Step 2: Fix the Functional Margin Scale

Because scaling both ww and bb by any arbitrary constant c>0c > 0 does not change the hyperplane {x:(cw)Tx+cb=0}\{x : (cw)^T x + cb = 0\}, we can fix the functional margin of the closest point to 11:

min⁡i=1,…,Nyi(wTxi+b)=1\min_{i=1,\dots,N} y_i(w^T x_i + b) = 1

This introduces the constraint yi(wTxi+b)≥1y_i(w^T x_i + b) \ge 1 for all i=1,…,Ni = 1, \dots, N.

3

Step 3: Formalize the Objective

With the numerator set to 11, maximizing the geometric margin 1∥w∥2\frac{1}{\|w\|_2} is equivalent to minimizing its reciprocal ∥w∥2\|w\|_2.

For mathematical convenience in differentiation, we minimize 12∥w∥22\frac{1}{2}\|w\|_2^2:

min⁡w,b12∥w∥22subject toyi(wTxi+b)≥1,∀i=1,…,N\min_{w, b} \frac{1}{2} \|w\|_2^2 \quad \text{subject to} \quad y_i(w^T x_i + b) \ge 1, \quad \forall i = 1, \dots, N

2. Soft-Margin SVM & Slack Variables#

Real-world datasets contain label noise and overlapping distributions where no linear hyperplane can achieve 100% clean separation.

To tolerate controlled margin violations, Cortes and Vapnik introduced non-negative slack variables ξi≥0\xi_i \ge 0:

min⁡w,b,ξ12∥w∥22+C∑i=1Nξisubject toyi(wTxi+b)≥1−ξi,ξi≥0\min_{w, b, \xi} \frac{1}{2} \|w\|_2^2 + C \sum_{i=1}^N \xi_i \quad \text{subject to} \quad y_i(w^T x_i + b) \ge 1 - \xi_i, \quad \xi_i \ge 0
  • If ξi=0\xi_i = 0: The point is correctly classified outside or on the margin.
  • If 0<ξi≤10 < \xi_i \le 1: The point violates the margin but remains on the correct side of the decision boundary.
  • If ξi>1\xi_i > 1: The point is misclassified.
  • Hyperparameter CC: Controls the penalty for margin violations. Large CC enforces hard margins (high variance), while small CC tolerates errors to widen the margin (high bias).

3. The Dual Problem and KKT Optimality Conditions#

To solve this constrained optimization problem, we construct the Lagrangian function with dual multipliers αi≥0\alpha_i \ge 0 and βi≥0\beta_i \ge 0:

L(w,b,ξ,α,β)=12∥w∥22+C∑i=1Nξi−∑i=1Nαi[yi(wTxi+b)−1+ξi]−∑i=1Nβiξi\mathcal{L}(w, b, \xi, \alpha, \beta) = \frac{1}{2} \|w\|_2^2 + C \sum_{i=1}^N \xi_i - \sum_{i=1}^N \alpha_i \Big[ y_i(w^T x_i + b) - 1 + \xi_i \Big] - \sum_{i=1}^N \beta_i \xi_i

First-Order Karush-Kuhn-Tucker (KKT) Stationarity#

Setting partial derivatives with respect to primal variables to zero:

  1. With respect to ww:
∇wL=w−∑i=1Nαiyixi=0  ⟹  w=∑i=1Nαiyixi\nabla_w \mathcal{L} = w - \sum_{i=1}^N \alpha_i y_i x_i = 0 \implies w = \sum_{i=1}^N \alpha_i y_i x_i
  1. With respect to bb:
∂L∂b=−∑i=1Nαiyi=0  ⟹  ∑i=1Nαiyi=0\frac{\partial \mathcal{L}}{\partial b} = -\sum_{i=1}^N \alpha_i y_i = 0 \implies \sum_{i=1}^N \alpha_i y_i = 0
  1. With respect to ξi\xi_i:
∂L∂ξi=C−αi−βi=0  ⟹  αi+βi=C\frac{\partial \mathcal{L}}{\partial \xi_i} = C - \alpha_i - \beta_i = 0 \implies \alpha_i + \beta_i = C

Substituting into the Lagrangian (The Wolfe Dual)#

Substituting these stationarity relations back into L\mathcal{L} eliminates primal variables ww, bb, and ξ\xi:

max⁡α∑i=1Nαi−12∑i=1N∑j=1Nαiαjyiyj(xiTxj)\max_{\alpha} \sum_{i=1}^N \alpha_i - \frac{1}{2} \sum_{i=1}^N \sum_{j=1}^N \alpha_i \alpha_j y_i y_j (x_i^T x_j)
subject to0≤αi≤C,and∑i=1Nαiyi=0\text{subject to} \quad 0 \le \alpha_i \le C, \quad \text{and} \quad \sum_{i=1}^N \alpha_i y_i = 0
Support Vector Sparsity via KKT Slackness
The KKT complementary slackness conditions state:
αi⋅[yi(wTxi+b)−1+ξi]=0\alpha_i \cdot \Big[ y_i(w^T x_i + b) - 1 + \xi_i \Big] = 0
- For any point strictly beyond the margin, yi(wTxi+b)>1  ⟹  αi=0y_i(w^T x_i + b) > 1 \implies \alpha_i = 0. These points contribute zero to parameter ww. - Only points on or violating the margin have αi>0\alpha_i > 0. These crucial points are the Support Vectors.

4. The Kernel Trick: Infinite Dimensional Feature Spaces#

Observe that the dual objective and inference decision rule depend solely on the inner product between feature vectors:

f(x)=sign(∑i=1Nαiyi(xiTx)+b)f(x) = \text{sign}\left( \sum_{i=1}^N \alpha_i y_i (x_i^T x) + b \right)

If data is non-linear in input space Rd\mathbb{R}^d, we map it via non-linear feature expansion ϕ(x)∈H\phi(x) \in \mathcal{H} into a higher-dimensional Hilbert space where linear separation is achievable.

By Mercer's Theorem, any symmetric positive semi-definite function K(x,z)K(x, z) computes this inner product directly without ever explicitly materializing high-dimensional vector ϕ(x)\phi(x):

K(x,z)=⟨ϕ(x),ϕ(z)⟩K(x, z) = \langle \phi(x), \phi(z) \rangle

Mathematical Proof: RBF Kernel as Infinite Dimensions#

The Radial Basis Function (Gaussian) kernel is:

K(x,z)=exp⁡(−γ∥x−z∥22)=exp⁡(−γ∥x∥22)exp⁡(−γ∥z∥22)exp⁡(2γxTz)K(x, z) = \exp\left( -\gamma \|x - z\|_2^2 \right) = \exp\left( -\gamma \|x\|_2^2 \right) \exp\left( -\gamma \|z\|_2^2 \right) \exp(2\gamma x^T z)

Applying the Taylor series expansion of eu=∑k=0∞ukk!e^u = \sum_{k=0}^\infty \frac{u^k}{k!}:

exp⁡(2γxTz)=∑k=0∞(2γ)kk!(xTz)k\exp(2\gamma x^T z) = \sum_{k=0}^\infty \frac{(2\gamma)^k}{k!} (x^T z)^k

Because (xTz)k(x^T z)^k is the polynomial kernel generating all polynomial terms up to degree kk, the infinite series summation proves that the RBF kernel maps inputs into an infinite-dimensional reproducing kernel Hilbert space (RKHS).

5. From-Scratch Implementation: Zero Dependencies#

The following implementations solve Linear SVM using subgradient descent on the regularized Hinge Loss:

J(w,b)=1N∑i=1Nmax⁡(0,1−yi(wTxi+b))+λ2∥w∥22J(w, b) = \frac{1}{N} \sum_{i=1}^N \max\Big(0, 1 - y_i(w^T x_i + b)\Big) + \frac{\lambda}{2} \|w\|_2^2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
from typing import List class LinearSVMFromScratch: def __init__(self, learning_rate: float = 0.001, lambda_param: float = 0.01, num_epochs: int = 1000): self.learning_rate = learning_rate self.lambda_param = lambda_param self.num_epochs = num_epochs self.weights: List[float] = [] self.bias: float = 0.0 def fit(self, X: List[List[float]], y: List[int]) -> None: # Expect labels in {-1, +1} num_samples = len(X) num_features = len(X[0]) self.weights = [0.0] * num_features self.bias = 0.0 for _ in range(self.num_epochs): for i in range(num_samples): # Functional margin: y_i * (w^T x_i + b) linear_output = sum(self.weights[j] * X[i][j] for j in range(num_features)) + self.bias condition = y[i] * linear_output >= 1.0 if condition: # Only regularization gradient for j in range(num_features): self.weights[j] -= self.learning_rate * (self.lambda_param * self.weights[j]) else: # Regularization + Hinge loss subgradient for j in range(num_features): self.weights[j] -= self.learning_rate * ( self.lambda_param * self.weights[j] - y[i] * X[i][j] ) self.bias += self.learning_rate * y[i] def predict(self, X: List[List[float]]) -> List[int]: num_features = len(self.weights) predictions = [] for row in X: score = sum(self.weights[j] * row[j] for j in range(num_features)) + self.bias predictions.append(1 if score >= 0.0 else -1) return predictions if __name__ == "__main__": X_train = [[1.0, 2.0], [2.0, 3.0], [2.0, 1.0], [6.0, 7.0], [7.0, 8.0], [8.0, 6.0]] y_train = [-1, -1, -1, 1, 1, 1] svm = LinearSVMFromScratch(learning_rate=0.01, lambda_param=0.01, num_epochs=500) svm.fit(X_train, y_train) preds = svm.predict(X_train) print(f"Learned weights: {svm.weights}") print(f"Learned bias: {svm.bias:.4f}") print(f"Predictions: {preds}")

6. Active Knowledge Checks#

Concept check

In the dual formulation of Support Vector Machines, what happens to training samples that lie strictly on the correct side of the margin boundary with margin > 1?

Concept check

Why can the Radial Basis Function (RBF) Gaussian kernel separate datasets that are non-linearly separable in any finite-dimensional polynomial feature space?