JMU CS 445: Support Vector Machines

Some examples adapted from Andrew Moore's machine learning tutorials: http://www.cs.cmu.edu/~awm/tutorials/

Where Should We Draw the Line?

  • Many lines separate these classes perfectly. Which one will generalize best?
  • Margin: the distance from the boundary to the closest point
  • SVM: choose the boundary with the maximum margin
  • The points on the edge of the margin are the support vectors. Move any other point (without crossing into the band): nothing changes.

Finding the Boundary

  • A hyperplane: w⊤x+b=0\mathbf{w}^\top\mathbf{x} + b = 0

  • Labels are t(i)∈{−1,+1}t^{(i)} \in \{-1, +1\}. Classify with y^=sign(w⊤x+b)\hat{y} = \text{sign}(\mathbf{w}^\top\mathbf{x} + b)

  • Being on the correct side isn't enough. We want some room:

    Instead of this:w⊤x(i)+b>0   for t(i)=+1,w⊤x(i)+b<0   for t(i)=−1We want this:w⊤x(i)+b≥1   for t(i)=+1,w⊤x(i)+b≤−1   for t(i)=−1Which is the same as this:t(i)(w⊤x(i)+b)≥1\begin{aligned} &\text{Instead of this:} && \mathbf{w}^\top\mathbf{x}^{(i)} + b > 0 \;\text{ for } t^{(i)} = +1, && \mathbf{w}^\top\mathbf{x}^{(i)} + b < 0 \;\text{ for } t^{(i)} = -1\\[4pt] &\text{We want this:} && \mathbf{w}^\top\mathbf{x}^{(i)} + b \geq 1 \;\text{ for } t^{(i)} = +1, && \mathbf{w}^\top\mathbf{x}^{(i)} + b \leq -1 \;\text{ for } t^{(i)} = -1\\[4pt] &\text{Which is the same as this:} && t^{(i)}(\mathbf{w}^\top\mathbf{x}^{(i)} + b) \geq 1 \end{aligned}

One Input: The Flattest Line

One feature xx. The score is wx+bwx + b.

  • Draw each point at height t(i)t^{(i)}: +1+1 or −1-1
  • The constraint t(i)(wx(i)+b)≥1t^{(i)}(wx^{(i)} + b) \geq 1: the line passes on or above every blue and on or below every red
  • Lay the line down as flat as it will go: minimize ∣w∣|w|
  • It comes to rest on the closest point of each class (the support vectors) and crosses 0 exactly halfway between them

Two Inputs: The Flattest Plane

Same idea, one dimension up.

  • Lift each point to height t(i)t^{(i)}
  • The score w⊤x+b\mathbf{w}^\top\mathbf{x} + b is a plane. It must pass on or above the blues and on or below the reds.
  • Make it as flat as possible: minimize ∥w∥\|\mathbf{w}\|. Now three support vectors hold it in place.
  • From above: the plane crosses 0 at the boundary and ±1\pm 1 at the edges of the margin

Why Flat Means Wide

  • The distance from a point x\mathbf{x} to the boundary is ∣w⊤x+b∣∥w∥\dfrac{|\mathbf{w}^\top\mathbf{x} + b|}{\|\mathbf{w}\|}

  • The support vectors have ∣w⊤x+b∣=1|\mathbf{w}^\top\mathbf{x} + b| = 1, so the margin is 1∥w∥\dfrac{1}{\|\mathbf{w}\|}

  • ∥w∥\|\mathbf{w}\| is the slope of the plane: flatter plane, wider margin

  • Maximizing the margin 1∥w∥\dfrac{1}{\|\mathbf{w}\|} is the same as minimizing 12∥w∥2\tfrac{1}{2}\|\mathbf{w}\|^2

  • The hard margin SVM:

    minimizew,b    12∥w∥2⏟sets the marginsubject to    t(i)(w⊤x(i)+b)≥1⏟every point on the correct side    for i=1,…,m\underset{\mathbf{w}, b}{\text{minimize}} \;\; \underbrace{\tfrac{1}{2}\|\mathbf{w}\|^2}_{\text{sets the margin}} \qquad \text{subject to} \;\; \underbrace{t^{(i)}(\mathbf{w}^\top\mathbf{x}^{(i)} + b) \geq 1}_{\text{every point on the correct side}} \;\; \text{for } i = 1, \dots, m

    (The textbook writes 12w⊤w\tfrac{1}{2}\mathbf{w}^\top\mathbf{w}: the same thing, since ∥w∥2=w⊤w\|\mathbf{w}\|^2 = \mathbf{w}^\top\mathbf{w})

Quadratic Programming

minimizew,b    12∥w∥2subject to    t(i)(w⊤x(i)+b)≥1\underset{\mathbf{w}, b}{\text{minimize}} \;\; \tfrac{1}{2}\|\mathbf{w}\|^2 \qquad \text{subject to} \;\; t^{(i)}(\mathbf{w}^\top\mathbf{x}^{(i)} + b) \geq 1

  • Minimizing a quadratic function subject to linear constraints... So what?
  • This is a (convex) quadratic programming (QP) problem
    • One minimum: no local minima to get stuck in
    • Good off-the-shelf solvers exist

What If the Data Isn't Separable?

  • Add a slack variable ζ(i)≥0\zeta^{(i)} \geq 0 for each point: how far it is allowed to violate its constraint

    minimizew,b,ζ    12∥w∥2+C∑i=1mζ(i)subject to    t(i)(w⊤x(i)+b)≥1−ζ(i),    ζ(i)≥0\underset{\mathbf{w}, b, \boldsymbol{\zeta}}{\text{minimize}} \;\; \tfrac{1}{2}\|\mathbf{w}\|^2 + C\sum_{i=1}^{m}\zeta^{(i)} \qquad \text{subject to} \;\; t^{(i)}(\mathbf{w}^\top\mathbf{x}^{(i)} + b) \geq 1 - \zeta^{(i)}, \;\; \zeta^{(i)} \geq 0

  • The hyperparameter CC is the price of a violation

  • Still a convex quadratic program, so the same solvers apply

Slack in 3D

  • The earlier data, plus one blue point deep among the reds: not separable
  • Hard margin (C=∞C = \infty): no solution at all
  • C=1000C = 1000: violations are expensive, but one can't be avoided. The orange bar is its slack ζ(i)\zeta^{(i)}: how far the plane is on the wrong side of the point.
  • C=0.1C = 0.1: slack is cheaper. Flatter plane, wider margin, more points inside it.
  • C=0.01C = 0.01: nearly every point is a support vector

Lagrange Multipliers

  • Lagrange multipliers convert a constrained optimization problem into an unconstrained one, with one new variable α(i)≥0\alpha^{(i)} \geq 0 per constraint:

    L(w,b,α)=12∥w∥2−∑i=1mα(i)(t(i)(w⊤x(i)+b)−1)\mathcal{L}(\mathbf{w}, b, \boldsymbol{\alpha}) = \tfrac{1}{2}\|\mathbf{w}\|^2 - \sum_{i=1}^{m} \alpha^{(i)}\Big(t^{(i)}(\mathbf{w}^\top\mathbf{x}^{(i)} + b) - 1\Big)

  • Each α(i)\alpha^{(i)} goes with one training point

  • We don't care about the details: this is just where the α\alpha's in the next formulas come from

    • (Shown for the hard margin. Slack adds a few more terms.)

The Dual Problem

  • The same problem, rewritten so that only the α\alpha's are unknown:

    minimizeα    12∑i=1m∑j=1mα(i)α(j)t(i)t(j) x(i)⊤x(j)  −  ∑i=1mα(i)\underset{\boldsymbol{\alpha}}{\text{minimize}} \;\; \frac{1}{2}\sum_{i=1}^{m}\sum_{j=1}^{m} \alpha^{(i)}\alpha^{(j)}t^{(i)}t^{(j)}\,{\mathbf{x}^{(i)}}^\top\mathbf{x}^{(j)} \; - \; \sum_{i=1}^{m}\alpha^{(i)}

    subject to 0≤α(i)≤C,    ∑i=1mα(i)t(i)=0\text{subject to } 0 \leq \alpha^{(i)} \leq C, \;\; \sum_{i=1}^{m}\alpha^{(i)}t^{(i)} = 0

    (The slack variables vanish: all that is left of them is the cap CC. With C=∞C = \infty it is the hard margin.)

  • Once we have the α\alpha's, we get the weights back:

    w^=∑i=1mα^(i)t(i)x(i)\hat{\mathbf{w}} = \sum_{i=1}^{m} \hat{\alpha}^{(i)}t^{(i)}\mathbf{x}^{(i)}

Two Things to Notice

  • The weights: most of the α(i)\alpha^{(i)} come out 0. The nonzero ones belong to the support vectors.

    w^=∑i=1mα^(i)t(i)x(i)\hat{\mathbf{w}} = \sum_{i=1}^{m} \hat{\alpha}^{(i)}t^{(i)}\mathbf{x}^{(i)}

  • The objective: the inputs only show up in the form of dot products between pairs of points

    12∑i=1m∑j=1mα(i)α(j)t(i)t(j) x(i)⊤x(j)  −  ∑i=1mα(i)\frac{1}{2}\sum_{i=1}^{m}\sum_{j=1}^{m} \alpha^{(i)}\alpha^{(j)}t^{(i)}t^{(j)}\,\textcolor{#d1620a}{{\mathbf{x}^{(i)}}^\top\mathbf{x}^{(j)}} \; - \; \sum_{i=1}^{m}\alpha^{(i)}

What About This Case?

  • Not linearly separable. Slack variables?
  • The best line still gets several points wrong
  • These points aren't noise: the boundary should bend
  • But an SVM can only draw a straight boundary...

One Feature, Not Separable

  • Where would a linear SVM put the decision boundary?
  • Add a feature: z=(x,x2)\mathbf{z} = (x, x^2)
    • Careful: up is now a feature, x2x^2, not the score
  • In 2-D the classes are linearly separable
  • Back in 1-D, the line becomes two thresholds: a nonlinear boundary

Two Features: Lift onto a Bowl

  • No line separates the center from the ring
  • Add a third feature: x12+x22x_1^2 + x_2^2 (squared distance from the origin)
    • Careful: up is the new feature again, not the score
  • Now a flat plane separates them
  • The plane slices the bowl along a closed curve
  • From above: a circular decision boundary in the original space

The Blessing of Dimensionality (?)

  • This works in general
  • When you increase the dimensionality of your data, you increase the chance that it will be linearly separable
  • In an N−1N-1 dimensional space you should always be able to separate NN data points. (Unless you are unlucky.)

Let's Do It!

  • Define a function ϕ(x)\phi(\mathbf{x}) that maps our low dimensional data into a very high dimensional space

  • Now just rewrite the optimization to use the high dimensional vectors:

    minimizeα    12∑i=1m∑j=1mα(i)α(j)t(i)t(j) ϕ(x(i))⊤ϕ(x(j))  −  ∑i=1mα(i)\underset{\boldsymbol{\alpha}}{\text{minimize}} \;\; \frac{1}{2}\sum_{i=1}^{m}\sum_{j=1}^{m} \alpha^{(i)}\alpha^{(j)}t^{(i)}t^{(j)}\,\textcolor{#d1620a}{\phi(\mathbf{x}^{(i)})^\top\phi(\mathbf{x}^{(j)})} \; - \; \sum_{i=1}^{m}\alpha^{(i)}

    subject to 0≤α(i)≤C,    ∑i=1mα(i)t(i)=0\text{subject to } 0 \leq \alpha^{(i)} \leq C, \;\; \sum_{i=1}^{m}\alpha^{(i)}t^{(i)} = 0

  • What's the problem?

The Kernel Trick

  • It turns out we can often find a kernel function KK such that

    K(a,b)=ϕ(a)⊤ϕ(b)K(\mathbf{a}, \mathbf{b}) = \phi(\mathbf{a})^\top\phi(\mathbf{b})

    computed without ever computing ϕ\phi

  • Example: ϕ(x)=(x12,  2 x1x2,  x22)\phi(\mathbf{x}) = \big(x_1^2,\; \sqrt{2}\,x_1x_2,\; x_2^2\big)

    ϕ(a)⊤ϕ(b)=a12b12+2a1b1a2b2+a22b22=(a1b1+a2b2)2=(a⊤b)2\phi(\mathbf{a})^\top\phi(\mathbf{b}) = a_1^2b_1^2 + 2a_1b_1a_2b_2 + a_2^2b_2^2 = (a_1b_1 + a_2b_2)^2 = (\mathbf{a}^\top\mathbf{b})^2

  • A 2-D dot product and a square gives the 3-D dot product. With higher powers and more features, ϕ\phi gets enormous but KK stays cheap.

  • In fact, almost any reasonable similarity function corresponds to a dot product in some space

Kernel Machines

  • Replace every dot product with KK:

    minimizeα    12∑i=1m∑j=1mα(i)α(j)t(i)t(j) K(x(i),x(j))  −  ∑i=1mα(i)\underset{\boldsymbol{\alpha}}{\text{minimize}} \;\; \frac{1}{2}\sum_{i=1}^{m}\sum_{j=1}^{m} \alpha^{(i)}\alpha^{(j)}t^{(i)}t^{(j)}\,\textcolor{#d1620a}{K(\mathbf{x}^{(i)}, \mathbf{x}^{(j)})} \; - \; \sum_{i=1}^{m}\alpha^{(i)}

    subject to 0≤α(i)≤C,    ∑i=1mα(i)t(i)=0\text{subject to } 0 \leq \alpha^{(i)} \leq C, \;\; \sum_{i=1}^{m}\alpha^{(i)}t^{(i)} = 0

  • Predictions need only the support vectors:

    h(x)=∑α^(i)>0α^(i)t(i)K(x(i),x)+b^h(\mathbf{x}) = \sum_{\hat{\alpha}^{(i)} > 0} \hat{\alpha}^{(i)}t^{(i)}K(\mathbf{x}^{(i)}, \mathbf{x}) + \hat{b}

  • We get to classify in very high dimensional spaces for almost no additional cost

  • Support vector machines are also called kernel machines

Some Kernels

Kernel K(a,b)K(\mathbf{a}, \mathbf{b})
Linear a⊤b\mathbf{a}^\top\mathbf{b}
Polynomial (γ a⊤b+r)d(\gamma\,\mathbf{a}^\top\mathbf{b} + r)^d
Gaussian RBF exp⁡(−γ ∥a−b∥2)\exp(-\gamma\,\lVert\mathbf{a} - \mathbf{b}\rVert^2)
Sigmoid tanh⁡(γ a⊤b+r)\tanh(\gamma\,\mathbf{a}^\top\mathbf{b} + r)
  • Choosing the kernel (and γ\gamma, rr, dd) is part of choosing the model
  • A 10th-degree polynomial kernel corresponds to a huge feature space (every product of up to 10 features), but computing KK is still just a dot product and a power

The RBF Kernel: Hills and Valleys

h(x)=∑α(i)t(i)e−γ∥x−x(i)∥2+bh(\mathbf{x}) = \sum \alpha^{(i)}t^{(i)}e^{-\gamma\|\mathbf{x} - \mathbf{x}^{(i)}\|^2} + b

  • Each support vector adds a bump: up for blue, down for red. The boundary is sea level, h=0h = 0.
  • Large γ\gamma: narrow bumps, a boundary that hugs every point (overfitting)
  • Small γ\gamma: broad bumps, close to a tilted plane (underfitting)

Nice Things About SVMs

  • Good generalization because of margin maximization
  • Not many hyperparameters to pick
    • No learning rate, no hidden layer sizes
    • Just CC, the kernel, and its parameters (γ\gamma, dd, ...)
  • No problems with local minima
  • What about SVM regression? It's possible, but we won't talk about it
  • The catch: the double sum is over every pair of training points. Training cost grows at least quadratically with mm, so 100 million points is not practical.

Interactive figures are drawn by svm_demos.js (pure canvas, no libraries). Every SVM in them is really trained, in the browser, by a small SMO solver that matches sklearn's SVC. Build with marp --html svm.md --html is required: the demos are inline <div>s plus a <script>. Bullets written with "*" unfold one at a time, and on demo slides each reveal also advances the animation, so the clicker drives everything. Mouse interaction (dragging, sliders, buttons) is extra and only affects the window you use it in. Every 3D figure can be dragged to rotate. Notation follows the reading (Geron, Appendix C): labels t in {-1, +1}, superscript (i) for instance i, m instances, alpha for the Lagrange multipliers, zeta for slack, and the gamma / r / d kernel parameters. The previous LibreOffice version of this deck is svm.odp / svm.pdf. svm_3d.py (plotly) is the prototype for the "flattest plane" demo, and svm_demos.py is the old matplotlib click-to-add-points demo.

We've spent weeks deep in neural networks. Today we drift back toward more traditional ML. There are lots of formulas today, because one of the two cool tricks only makes sense once you've seen what is being optimized. You won't be tested on the minutiae of the formulas.

Idea 1 of 2: maximum margin. The data are samples from some underlying distribution; keeping the boundary as far from all of them as possible makes it least likely we put it in the wrong place. In 2-D, three points typically pin the boundary down. On the last step you can drag points around: the SVM retrains live. Drag a non-support vector around (nothing happens) and then a support vector.

This is the same w^T x + b we used for linear regression and logistic regression: one set of weights is one plane. Multiplying by t flips the inequality for the negative class, which is why we use -1/+1 labels here instead of 0/1.

This is the board drawing from last year. Click 2 shows a steep line that satisfies every constraint, but where it crosses zero (the boundary) is much closer to the red point than to the blue one. Click 3 lays it down: the slope shrinks until the line bumps into one point from each class and can't go any flatter. At that point the two distances under the axis are equal: that's the maximum margin, 1/w on each side. Q from class: "why do we want it flat?" Only because flattest forces the zero crossing to the midpoint. The w slider and dragging the line show that any steeper line has slack in where it can sit.

This replaces the old "Visualizing the Boundary" and "Two Boundaries" slides: those were this picture seen from straight above. Any w is a plane, exactly like linear regression. The dashed lines are where the plane crosses +1 and -1; the green line is where it crosses 0. Watch the readout while it flattens: ||w|| goes down and the margin 1/||w|| goes up. The gray band on the floor is the margin. In 1-D it took two points to pin the line; here it takes three.

Squaring gets rid of the square root in ||w||: same minimizer, but smooth and quadratic, which matters on the next slide. The 1/2 just makes the derivative cleaner.

A numerical optimization course in the math department would cover these. Unlike all the neural network loss surfaces we've been looking at, this one has a unique minimum and we're guaranteed to find it.

Huge C: violations are very expensive. C = infinity is the hard margin SVM, which has no solution at all if the data aren't separable. Small C: we barely care, and happily trade violations for a wide margin.

No plane puts the stray blue point on the blue side, so the hard margin SVM has no solution. C = 1000: the solver accepts the one unavoidable violation (slack about 2.2: the point is misclassified, so its slack is more than 1) and otherwise keeps every point outside the margin (1.11). C = 0.1: margin 1.60, eight support vectors, a few small bars appear. C = 0.01: margin 3.64, lots of slack, 16 of 17 points are support vectors. Ringed points are support vectors: everything on or inside the margin. The slider is log10 C. The activity's (2, 6) point is the same situation: C = infinity has no solution, a finite C trades slack for margin.

Everybody hates constrained optimization. Each constraint becomes an extra term in the function we optimize, and its multiplier becomes one more parameter to solve for. (The old slide had a stray 1/2 in front of the sum.)

"Dual" problem: guaranteed to have the same answer, expressed differently. The solver works on this one. Written the way the reading writes it, as a minimization; some sources negate it and maximize.

This second observation is the whole reason we went through the dual. We don't need the data itself to do the optimization, only the dot product between every pair of points. Hold that thought.

Idea 2 of 2 starts here. Slack is for the occasional stray point. Here the classes are clean; the true boundary is just not a line, and paying slack on five points would be papering over the real problem. The curve is an RBF SVM, which is where we end up today.

SVMs can only ever draw linear boundaries. But nothing stops us from adding features computed from the ones we have, moving the data to a higher dimensional space where it is more likely to be linearly separable.

Every point sits on the bowl z = x1^2 + x2^2. The SVM is trained on the 3-D points; three support vectors again. The green ring is where the plane cuts the bowl; its shadow on the floor is the decision boundary in the original 2-D space. Any plane cuts this bowl in a circle, so with this feature map the SVM can draw any circle (or a line).

Table discussion. Answer: the double sum is already quadratic in the number of training points, and each of those m^2 dot products now costs time proportional to the new dimensionality. Going from 2 to 10,000 dimensions makes every one of them thousands of times slower (and we have to compute and store all the phi vectors).

Through the power of math and magic, a cheap function of the two low-dimensional vectors gives exactly the number we'd get by projecting into the big space and taking the dot product there. How to find these functions is beyond this class (Mercer's theorem). The activity has a 6-D version of this example: (a^T b + 1)^2.

We never compute w in the big space (it might not even be finite), but we never need it: h(x) is w^T phi(x) + b written with K. 1998: kernel methods were what deep learning is now. Reams of papers on "kernelizing" every algorithm in sight.

Notation now matches the reading. The old slides wrote the RBF kernel with sigma: gamma = 1 / (2 sigma^2). The reading has a nice discussion of when to use which kernel. The RBF kernel's feature space is infinite dimensional.

Step 0 is the usual 2-D picture: decision regions, the boundary in green, margins dashed. Click 1 tips it up: the same picture is a landscape. Compare with the linear SVM: there the landscape was a plane. Each point sits on the surface at height h(x); support vectors are ringed. gamma = 5: 26 of 32 points are support vectors, each with its own spike. gamma = 0.05: almost a plane, and several points end up on the wrong side. C = 10 throughout. Slider is log10 gamma.

SVMs are still useful, which is why we're covering them: small to medium data sets, lots of features, little tuning.