Kernels

A kernel is a shortcut. It lets a flat plane cut data that no straight line could, in a space with millions of extra features, without ever building one of them.

Learn how the support vector machine becomes a curved classifier: the geometry of the dual, the lift, the kernel that skips the lift, and the test that says which functions are kernels.

Pick Rings, drag Lift to the top, then slide the Plane until every point is on its own side. A flat cut up in 3-D leaves a circle on the floor. Then we build, piece by piece, the geometry, the lift, the kernel and a machine you can train.

You need a dot product (multiply two lists of numbers entry by entry, then add) and the support vector machine from the last two lessons. We recap both.

Based on Lecture 11 of Stanford EE269: Signal Processing for Machine Learning, taught by Mert Pilanci (Winter 2019), here our Lecture 19. Lecture slides and the course slide index. All figures and devices are our own.

Lift the data, cut with a plane

0%
4.5

Toy data, 44 points made with a fixed seed (illustrative). Rings lift by z = x₁² + x₂². XOR corners lift by z = x₁·x₂. Both are the feature maps of Chapter 3.

Chapter 0

A Straight Line Is Not Enough

See what a line can and cannot cut, and recall the SVM and its dual that the rest of the lecture bends

A vibration sensor on a pump reports two numbers every second: x1 and x2, its readings on two axes. When the pump runs quietly, both numbers stay near zero. When something is wrong, the readings swing wide, but in any direction. Plot many seconds and you see a dense blob with a ring of alarm points around it.

You want a rule that says “quiet” or “alarm” for a new reading. The simplest rule is a linear classifier: a straight line in the plane, with “quiet” on one side and “alarm” on the other. Try it yourself below. The ring is the toy version of this pump.

Cut the rings with one line

Warm points are the quiet blob, blue points are the alarm ring. Turn the line and slide it. Red rings mark points on the wrong side. Then ask for the best of all the lines.

35°
0.60

Toy data (illustrative): 40 points from a fixed seed, an inner blob and an outer ring. A line may name either side “quiet”, so a score below half is flipped. The best line is found by trying 180 angles and 101 offsets.

No line gets every point right. The best of 18,180 lines still leaves a fifth of the points on the wrong side. The reason is geometry. A line splits the plane into two half-planes, and a ring has the blob on the inside and the alarms on all sides. No half-plane holds the blob without also holding some of the ring.

The linear classifier in one formula

Write a point as a list of numbers, x = (x1, x2). A line is the set of points where wTx + b = 0. The vector w (the weights) points across the line, and the number b (the bias) slides it. The symbol wTx is the dot product: w1x1 + w2x2.

The classifier is sign(wTx + b). A positive value says class +1. A negative value says class −1. The two sliders above are exactly w (the angle) and b (the offset).

Recap: the soft margin SVM

Many lines can split two clean groups. The support vector machine (SVM) picks the one with the widest empty street between the groups. The width of the street is 2/‖w‖, so a wide street means a short w. Real data overlaps, so the SVM lets each point i cross its street by a small amount si, called a slack variable. The lecture opens with this problem.

½‖w‖22
Half the squared length of w. Making this small makes the street wide.
C · (1/n) Σ si
The price of slack. C is a tuning knob: a large C punishes every crossing, a small C forgives them. The 1/n averages over the n points.
yi(wTxi + b) ≥ 1 − si
Point i, with label yi of +1 or −1, must sit at least 1 unit past the line, minus its slack.

Recap: the dual problem

The last lesson turned this problem inside out with convex duality. The new unknowns are one number αi per data point, a weight that says how much point i matters. Most αi end at zero. The points with a nonzero αi are the support vectors. The lesson before it built the primal form above.

−½ Σij αiαj yiyj xiTxj
A sum over every pair of points. It rewards pairs of different classes that sit far apart and punishes pairs of the same class that sit close.
xiTxj
The dot product of two data points. Hold on to this term. It is the only place the data enter the dual.
Σ αi
A reward for using weight at all, so the solver does not set every α to zero.
Σ αiyi = 0, 0 ≤ αi ≤ C/n
The two classes carry equal total weight, and no single point may carry more than C/n.
w* = Σ αi* yi xi
The best weights are a mix of the data points, each signed by its label.

This is the seed of the whole lecture. The data enter the dual only through dot products, and the answer is a mix of data points. If we can bend a line into a curve by changing only what the dot product means, the SVM draws curves for free.

The question for today. The sensor ring needs a curved boundary. The SVM draws only flat ones. Can we keep the SVM and still draw a circle?

The road

  1. The dual as geometry: why the SVM finds the closest points of two shapes.
  2. More than two classes: one score per class, and two shortcuts.
  3. Lifting: new features turn a circle into a flat cut. This is the hero you played.
  4. The kernel: the lifted dot product without the lift.
  5. Polynomial kernels: the features of any power, and how many there are.
  6. Valid kernels: the matrix test, and the Gaussian kernel.
  7. The kernel trick: swap the dot product and train.
  8. The kernel machine: predict by a vote, tune two knobs.
  9. Field guide: numbers, checklist, code.
Why can no straight line separate a blob from a ring around it?

Chapter 1

The Dual SVM Is a Distance Between Two Shapes

Turn the dual problem into a picture: find the two closest points of two convex hulls

Picture two clouds of pins stuck in a board: warm pins on the left, blue pins on the right. Stretch a rubber band around each cloud. Each band hugs its pins and encloses a flat shape. You now have two shapes with a gap between them. Where would you draw the fence?

Most people say: halfway across the narrowest part of the gap. That instinct is the support vector machine. This chapter proves it, using only the dual problem from Chapter 0 and a few steps of algebra. The proof matters later, because it shows that the SVM only ever cares about how far apart points are.

Start with the hard margin

First, remove slack. Let C grow without limit. A huge C makes any crossing of the street too expensive, so every point must stay on its own side. This is the hard margin SVM. In the dual, the cap C/n on each αi disappears. The double sum also collapses into one squared length, because summing over every pair i, j is the same as squaring the sum.

−½ ‖Σ αiyixi‖2
Minus half the squared length of one mixed vector. The mix is w, so this is minus half of ‖w‖2.
Σ αi
The total weight. The solver wants it large, but a large mix is costly in the first term.
Σ αiyi = 0, αi ≥ 0
Warm and blue weights must balance. No weight is negative.

Split the sum by class

Every label yi is +1 or −1. So the mixed vector is the warm points minus the blue points, each weighted by its α. Write i∈+ for the warm points and i∈− for the blue ones. The balance rule says the two groups carry equal total weight. The lecture then does six small moves, and each one is simple.

  1. Split. Σ αiyixi = Σ+ αixi − Σ− αixi, and Σ+ αi = Σ− αi.
  2. Name the common weight. Call that shared total γ. Then Σi αi = 2γ. Maximizing over γ as well changes nothing, because the α already fix γ.
  3. Rescale. Replace each αi by γαi. Now both groups sum to exactly 1, and the objective is −(γ²/2) D + 2γ. Here D is the squared length ‖Σ+ αixi − Σ− αixi‖2.
  4. Optimize γ. The slope in γ is −γD + 2. Setting it to zero gives γ* = 2/D.
  5. Plug it back. The value is −(2/D²)·D + 4/D, which equals 2/D.
  6. Read the result. Making 2/D large means making D small. So the dual asks for the smallest D over the weights that sum to 1 in each group.

Now name the shapes. A weighted average of some points is their balance point: give each point a weight of 0 or more, make the weights sum to 1, and add up weight times point. The set of all such averages of a cloud is its convex hull, the shape the rubber band makes. So Σ+ αixi is some point inside the warm hull. And Σ− αixi is some point inside the blue hull.

min ‖ … ‖2
Make the squared distance between two points as small as possible.
Σ+ αixi
A point somewhere in the warm hull, a weighted average of warm data points.
Σ− αixi
A point somewhere in the blue hull.
Σ+ αi = Σ− αi = 1, αi ≥ 0
The rule that makes each sum a true weighted average.

This is the slide’s punchline: the dual SVM is the minimum distance between two convex hulls. Drag the pins below. The teal bar joins the two closest points, one on each hull. The SVM fence stands in the middle of that bar, at a right angle to it.

Find the closest points of two hulls

Drag any pin, or slide the blue group toward the warm one. Labels show each support vector’s α. The dashed lines are the fence and the two edges of the street.

0.00

Toy pins (illustrative). The closest pair is found exactly: every hull vertex against every edge of the other hull. The α labels use αi = γ* × (the point’s weight in its hull).

One worked example, every step

Take two warm points A = (3, 0) and B = (3, 2), and one blue point C = (1, 1). The warm hull is the vertical segment from A to B. The blue hull is the single point C. The closest point of the segment to C is (3, 1), the midpoint, so the weights on A and B are 0.5 each.

The squared distance is D = ‖(3, 1) − (1, 1)‖2 = 4. So γ* = 2/4 = 0.5. The weights in the original scale are αA = αB = 0.5 × 0.5 = 0.25 and αC = 0.5 × 1 = 0.5. They balance: 0.25 + 0.25 − 0.5 = 0.

Now rebuild w. Use w* = Σ αiyixi = 0.25(3, 0) + 0.25(3, 2) − 0.5(1, 1) = (1, 0). The bias comes from a support vector on the street edge: 3 + b = 1, so b = −2. The blue point checks out: 1 − 2 = −1. The street is 2/‖w‖ = 2 units wide, which is exactly the distance between the hulls.

D = 4  →  γ* = 2/D = 0.5  →  w* = (1, 0), b = −2  →  street = 2/‖w*‖ = 2 = distance between hulls

When the hulls touch

Slide the blue group left in the device until the shapes overlap. The symptom is that the distance reads 0. The measurement is D = 0, so γ* = 2/D has no value: no fence can keep every point on its own side. The fix is the one Chapter 0 already holds. Bring the slack back with a finite C, and let a few points cross.

After the lecture’s steps, what does the hard-margin dual SVM compute?

Chapter 2

More Than Two Classes

Score every class with its own line, then compare the one-vs-all and one-vs-one shortcuts

A microphone is clamped to a motor. Every second it reports two numbers, summarizing the sound. The motor can be in one of three states: healthy, unbalanced, or a worn bearing. You want a rule that names the state. One line can only split the plane into two halves. Three states need a different idea.

The SVM so far answers a yes-or-no question. The lecture now extends it to K classes, with K = 3 here. There are two ways to do it, and the lecture shows both.

One score per class

Give every class its own line: a weight vector wk and a bias bk. For a point x, class k gets the score wkTx + bk. A big score means “this looks like class k.” The prediction is the class with the biggest score. The lecture’s prediction slide says exactly this.

Look at the shapes. A point x has d numbers. Stack the K weight vectors into a matrix W with K rows and d columns. Then W x + b is a list of K scores, and the arg max of that list is the answer. For the motor, d = 2 and K = 3, so W holds 6 numbers and b holds 3.

The training rule is the two-class street rule, repeated. The score of the correct class must beat every other class by a margin of 1, minus a slack si for point i. The lecture writes it like this.

½ Σk ‖wk‖2 + C · (1/n) Σ si
Keep every class’s weights short, so the streets stay wide, and keep the average slack small. This is the two-class objective with a sum over classes.
wkTxi + bk ≥ wk′Txi + bk′ + 1 − si
Here k is the true class yi of point i, and k′ is any wrong class. The true score must lead every wrong score by 1, unless slack si excuses it.
si ≥ 0
Slack is never negative. A point that wins by more than 1 has slack 0.

A worked point

Take the point x = (2, 1) with true class A. Suppose the three scores are 3.1 for A, 2.4 for B and −0.5 for C. The closest rival is B. The lead is 3.1 − 2.4 = 0.7. The rule asks for a lead of 1 − s, so 0.7 ≥ 1 − s, which gives s ≥ 0.3. The classifier is right, because A wins. But the point sits inside the margin, so it pays slack 0.3.

Only the nearest rival matters, because beating the closest rival by 1 also beats every farther rival by more than 1. Try it below. The button trains the three lines on 30 toy points with the lecture’s rule, using gradient steps.

Train three lines, one per class

Each tinted region is where one class has the top score. Press Train and watch the three lines settle. Ringed points are inside a margin or wrong.

10

Toy data (illustrative): three blobs of 10 points, a fixed seed. Training is plain subgradient descent on the lecture’s objective, step 0.05, so the lines are close to the optimum, not exact. The third class borrows purple.

Notice the regions meet at a point, and every border is a straight line. Each border is where two scores tie. A straight line is still all this method can draw. Chapter 3 fixes that.

Two shortcuts with binary SVMs

You can also reuse the two-class SVM you already have. The lecture offers two ways. In one vs all, train K binary SVMs: class k against every other class, for k = 1 to K. To predict, pick the class whose classifier gives the highest score. In one vs one, train one SVM for every pair of classes, which is K(K−1)/2 classifiers. To predict, let each pair vote, and pick the class with the most votes.

The counts grow quickly. With K = 10 classes, one vs all trains 10 SVMs and one vs one trains 45. With K = 26 letters of the alphabet, it is 26 and 325. But each one-vs-one SVM sees only two classes, so about 2n/K points instead of n.

Count the classifiers

Slide the number of classes K. The bars show how many binary SVMs each plan trains.

10

The counts K and K(K−1)/2 are the lecture’s. The cost line is our arithmetic and assumes training cost grows like n² and balanced classes (illustrative).

That last read-out is a reminder, not a rule. One vs one trains many more models, but each model is small. If training cost grows faster than the data size, the many small models can cost less in total. If it grows only in a line, one vs all wins. Ties in the vote need a rule too, for example adding up the decision values. That detail is not on the slide.

A point of true class A has scores A 3.1, B 2.4, C −0.5. What slack does the multi-class rule give it?

Chapter 3

Lifting: A Curve Becomes a Flat Cut

Add new features made from the old ones, and watch a circle turn into a plane

Go back to the sensor ring. The quiet blob sits at the centre, and the alarms circle it. No line cuts it. But a circle cuts it perfectly: inside the circle is quiet, outside is alarm. A circle is described by a centre (c1, c2) and a radius r. The rule is the lecture’s circular classifier, one line long.

class = sign( (x1 − c1)2 + (x2 − c2)2 − r2 )   (positive outside the circle, negative inside)

This rule is not linear in x, because x1 and x2 appear squared. The trick of this chapter is to ask a different question. Is it linear in other numbers built from x? Expand the squares and see.

Expand the circle

Multiply out the two brackets. You get x1² + x2² − 2c1x1 − 2c2x2 + (c1² + c2² − r²). Every term is a number times one of five ingredients: x1, x2, x1x2, x1² and x2², plus one constant. The lecture lists exactly these five as the feature map.

Φ(x)
The feature map. It takes a point with 2 numbers and returns 5 numbers built from them. In general Φ maps RN to RM.
wTΦ(x)
An ordinary dot product, now between a weight list and the five new features. This is linear in the features, though curved in x.
b
A single constant that carries the radius and the centre offset.

Here is a full check. Take the circle with centre (1, −0.5) and radius 1.5. Then w = (−2, 1, 0, 1, 1) and b = 1 + 0.25 − 2.25 = −1. Test the point x = (1, 0.5). Its features are Φ(x) = (1, 0.5, 0.5, 1, 0.25). The dot product is −2 + 0.5 + 0 + 1 + 0.25 = −0.25, and adding b gives −1.25. The negative sign says “inside.” The direct formula agrees: 0² + 1² − 2.25 = −1.25. Same number, two routes.

Build the circle from five weights

Move the circle. The bars on the right are the weights w and the bias b that the lifted linear rule needs to draw that exact circle.

0.00
0.00
0.60

Toy data (illustrative): 44 points of a ring pair centred at (0.8, −0.4), with a little radial noise. The score is computed with the five features, not with the circle formula, so the two always agree. “Best circle” scans centres and radii.

Lifting, as a picture

The lecture calls the map Φ a lift. Think of the flat plane as a sheet on the floor. Each point is pushed up to a height set by the new features. Take only the height z = x1² + x2². The sheet bends into a bowl. The blob at the centre sits at the bottom. The ring is up the walls. A flat cut across the bowl at height h now separates them. That is the hero at the top of this page.

Look at what the flat cut does back on the floor. The plane meets the bowl where x1² + x2² = h, which is a circle of radius √h. A tilted plane z = a x1 + b x2 + h gives a circle with centre (a/2, b/2) and radius² = h + (a² + b²)/4. So every circle is the shadow of some plane. Hyperplanes in the lifted space are curves in the original space. That is the whole idea of the lecture’s “Hyperplanes in lifted space” picture.

The same lift hides in signal detection

The lecture reminds us of an old friend from the Bayes classifier lesson. You record N samples x1, …, xN. Under class 1 they are pure noise with variance σ1². Under class 2 they are signal plus noise, with a larger variance σ2². The best rule, with prior chances π1 and π2, says “class 2” when the following holds.

(…) Σ xi2
A fixed positive number times the energy of the recording, the sum of its squared samples.
log(π1/π2) − (N/2) log(σ12/σ22)
A fixed threshold made of the priors, the sample count and the two variances.

Read it as a feature map. Let Φ(x) be the single number Σ xi². The rule is linear in that one feature: weight times Φ against a threshold. Here the lift goes down from N numbers to 1. The lesson is the same: choose features in which a flat rule works. A worked case: N = 64, σ1² = 1, σ2² = 2 and equal priors. The threshold on the energy is (64/2) ln 2 / (1/2 − 1/4) = 22.18 / 0.25 = 88.7. Pure noise has average energy 64. Signal plus noise has 128.

Detect a signal by its energy

Top: one recording of pure noise and one of signal plus noise. Bottom: the energy of 4,000 recordings of each. Drag the sliders and watch the two piles overlap.

64
2.0

Simulated Gaussian samples (illustrative), with σ1² = 1 and equal priors. The threshold is the lecture’s Bayes rule. The error is counted on the 8,000 simulated recordings.

More samples pull the piles apart, because energy adds up while its spread grows more slowly. A weaker signal pushes them together. At the overlap, no threshold is perfect, and that is the best that any classifier can do.

Why is a circle classifier “linear” after the lift Φ(x) = (x1, x2, x1x2, x1², x2²)?

Chapter 4

The Kernel: An Inner Product Without the Lift

Compute the dot product of two lifted points without lifting either one

Lifting a point from 2 numbers to 5 is cheap. Now picture a small grey image, 28 by 28 pixels, so 784 numbers. Add every product of two pixels, as the circle map added x1x2 and x1². The lifted point has 307,720 numbers. Do that for 60,000 images and your memory is gone before the SVM starts.

The lecture says it plainly: since Φ(x) is high dimensional, we may not compute it explicitly. Then it gives a way out. Look back at the dual SVM from Chapter 0. The data entered it in one place only: the dot product xiTxj. After a lift, that term becomes the dot product of two lifted points.

Define the kernel

Give that dot product a name. The kernel function of a feature map Φ takes two points and returns the dot product of their lifted versions.

κ(x, x′)
The kernel. It reads two points and returns one real number. Kappa is the Greek letter k.
⟨Φ(x), Φ(x′)⟩
The dot product of the two lifted points. It is large when the lifted points point the same way, and small when they do not.

The lecture adds three facts. A kernel is a real number from two arguments. It is usually symmetric, so κ(x, x′) = κ(x′, x). And it can be read as a similarity: a big value says “these two are alike.” The headline fact is the next one. A kernel can sometimes be computed fast even if Φ(x) is infinite dimensional. Let us see one that works.

A kernel you can check by hand

Take two points in the plane, x = (x1, x2) and y = (y1, y2). Define κ(x, y) = (xTy)²: take the ordinary dot product, then square it. Expand, one step at a time.

  1. Write the dot product. xTy = x1y1 + x2y2.
  2. Square it. (x1y1 + x2y2)² = x1²y1² + 2x1x2y1y2 + x2²y2².
  3. Split the 2. Write 2 as √2 times √2, one for each side: 2x1x2y1y2 = (√2 x1x2)(√2 y1y2).
  4. Read off the dot product. The three terms pair up as (x1²)(y1²) + (√2 x1x2)(√2 y1y2) + (x2²)(y2²). This is Φ(x)TΦ(y) with Φ(x) = (x1², √2 x1x2, x2²).

That is the lecture’s example, and its feature map has three entries. Now use real numbers. Let x = (1, 2) and y = (3, 1). Route one, the kernel: xTy = 3 + 2 = 5, and 5² = 25. Route two, the lift: Φ(x) = (1, 2√2, 4) and Φ(y) = (9, 3√2, 1). The products are 1×9 = 9, then (2√2)(3√2) = 12, then 4×1 = 4. The sum is 25. Both routes agree, but the first never built a lifted vector.

Two routes to the same number

Drag the tip of either arrow, or use the sliders. Left: the points. Right: the three lifted features, and the product of each pair. Their sum is always the squared dot product.

1.0
2.0
3.0
1.0

Exact arithmetic on the numbers you set. The multiplication counts are for d = 2: the kernel takes 2 for the dot product and 1 to square it, while building both lifted vectors takes 4 + 4 and their dot product takes 3.

Any dimension d

The same steps work for points with d numbers. Write the square of a sum as a double sum: (Σi xiyi)(Σj xjyj) = ΣiΣj (xixj)(yiyj). Each pair (i, j) gives one product of two lifted entries xixj and yiyj. Pairs with i ≠ j appear twice, once as (i, j) and once as (j, i). Merge each twin pair into one feature √2 xixj.

The lecture’s feature map has d squares x1², …, xd² and d(d−1)/2 cross terms, so d + d(d−1)/2 features in all. For d = 784 pixels that is 784 + 306,936 = 307,720 numbers. The kernel gets the same answer with 784 multiplications and one squaring.

d = 784:   lifted dot product ≈ 3 × 307,720 = 923,160 multiplications  vs  kernel = 785 multiplications

The bill moves, it does not vanish

Here is the symptom to watch for. Training stalls or runs out of memory on a kernel method, although the feature count looks harmless. The measurement is the kernel matrix, the table of κ for every pair of training points. It has n × n entries. For n = 60,000 images, that is 3.6 billion numbers, about 14 GB at 4 bytes each. This is our arithmetic, not the slide’s. The fix is to pick the smaller side of the trade. Lift explicitly when n is huge and the lifted dimension is small. Use the kernel when the lifted dimension is huge and n is moderate.

For κ(x, y) = (xTy)² with x = (1, 2) and y = (3, 1), what is κ(x, y), and what does it equal?

Chapter 5

Polynomial Kernels and the Feature Explosion

Find the feature map of any power, and count how many features the kernel saves you from building

The squared kernel gave us a lift with three features. What about a cube? The lecture hands us this as an exercise: for κ(x, y) = (xTy)3, find the feature map Φ(x). Let us do it for points in the plane, and then for any power.

The exercise: the cube in two dimensions

Expand (x1y1 + x2y2)3. Call a = x1y1 and b = x2y2. Then (a + b)3 = a3 + 3a2b + 3ab2 + b3. Put the letters back. The four terms are x13y13, then 3x12x2y12y2, then 3x1x22y1y22, then x23y23.

Each term is a product of an x-part and a y-part. The coefficient 3 splits as √3 × √3, one root per side, as the 2 did in Chapter 4. So the feature map has four entries.

Φ(x) = ( x13,  √3 x12x2,  √3 x1x22,  x23 )

Check with x = (1, 2) and y = (3, 1). The kernel route gives (xTy)3 = 53 = 125. The lifted route gives Φ(x) = (1, 2√3, 4√3, 8) and Φ(y) = (27, 9√3, 3√3, 1). The four products are 27, then (2√3)(9√3) = 54, then (4√3)(3√3) = 36, then 8. They add to 125.

Expand the power into features

Pick two points, then slide the power p. Each row is one feature. Its bar is the product of the two lifted entries. The bars always add to (x·y)p.

3

Exact arithmetic. The feature for the monomial x₁p−jx₂j is the square root of C(p, j) times that monomial, which is the lecture’s multinomial map with d = 2.

Any power, any dimension

The pattern is the multinomial theorem. A power of a sum expands into every way of choosing how many times each term is used. For d numbers and power p, the lecture writes it this way.

(xTy)p
The homogeneous polynomial kernel of power p.
Σ over j1 + … + jd = p
One term for every way to give each of the d inputs a whole-number exponent so the exponents add to p.
(p; j1, …, jd)
The multinomial coefficient p! / (j1! … jd!). It counts the orderings. For d = 2 it is the familiar C(p, j).
x1j1…xdjd
A monomial of degree p in x: inputs multiplied together, p factors in all.
y1j1…ydjd
The same monomial of y.

Split each coefficient into two square roots, one for each side, and the feature map is the list of √(coefficient) × monomial. The lecture’s summary is short: the features are all monomials of degree p.

The lecture also lists the inhomogeneous kernel (1 + xTy)p. The reason it works is a small trick. The number 1 + xTy is the dot product of (1, x) and (1, y), which are the points with a constant 1 glued on the front. So (1 + xTy)p is the homogeneous kernel in d + 1 dimensions. Its features are all monomials of degree up to p in the original d inputs, including the constant.

Counting the features

How many monomials of degree p exist in d inputs? Picture p identical balls dropped into d boxes, one box per input. A box’s count is its exponent. The number of ways is C(d + p − 1, p). For d = 2 that is p + 1, which matches the table: a square has 3 features and a cube has 4. For the inhomogeneous kernel the count is C(d + p, p).

Now watch the explosion. Take a 28 by 28 image, so d = 784. At p = 2 there are 307,720 features. At p = 3 there are 80,622,640, about 645 MB for one point stored at 8 bytes per number. At p = 4 there are 15.9 billion. The kernel costs the same 784 multiplications every time.

Count what the kernel saves you

Pick a real signal size, then slide the power. The top bar is the number of features of one lifted point. The bottom bar is the work of the kernel. Both scales are logarithmic.

3

Counts use C(d + p − 1, p), exact up to rounding in the largest. Memory assumes 8 bytes per number (illustrative). The kernel work is d multiplications for the dot product plus about log₂p to raise it to the power p.

How many features does (xTy)2 have for points with d = 10 numbers?

Chapter 6

Which Functions Are Kernels?

Test a similarity function with its kernel matrix, and meet the Gaussian kernel with its endless features

You have two short recordings of a machine, and you invent a score for how alike they are. Maybe it is minus the distance between them. Maybe it is how well their waves line up. Can you drop your score into an SVM as its kernel? The answer is not “any score works.” The lecture asks the exact question: when does κ(x, y) = ⟨Φ(x), Φ(y)⟩ hold? When can we find a feature map at all?

The answer: the kernel matrix must be positive semidefinite

Pick any n points x1, …, xn. Build the kernel matrix K, an n by n table where entry Kij = κ(xi, xj). The lecture’s answer is a definition. A kernel is a positive definite kernel if, for every choice of points, K is a symmetric positive semidefinite matrix.

What does that mean? A symmetric matrix K is positive semidefinite when vTKv ≥ 0 for every list v of n numbers. Think of vTKv as a squared length. A squared length is never negative. An equivalent test: all of K’s eigenvalues (the stretch factors of K along its special directions) are 0 or more.

Why a real feature map forces it

Suppose κ(x, y) really equals ⟨Φ(x), Φ(y)⟩. Then for any list v, the number vTKv is a squared length. Here is the short proof.

vTKv
Weigh the n points by v, then read off one number from the kernel matrix.
Σij vivj ⟨Φ(xi), Φ(xj)⟩
The same number written entry by entry, with each Kij replaced by its lifted dot product.
‖Σ viΦ(xi)‖2
The squared length of one lifted vector, a weighted sum of the lifted points. A squared length cannot be negative.

So every genuine kernel passes the test. The converse also holds, though the slide only states the definition: a function that passes it for all point sets does have a feature map, possibly with infinitely many entries. This is the content of Mercer’s theorem, a standard result from outside the slides. The next lesson on RKHS builds that feature space step by step.

A failing similarity, by hand

Test “minus the distance” on three numbers x = 0, 1, 2 with κ(x, y) = −|x − y|. The matrix is the table below. Its diagonal is all zeros, so its eigenvalues sum to 0, and they cannot all be zero because the off-diagonal entries are not. Some eigenvalue must be negative.

K = [ 0 −1 −2 ; −1 0 −1 ; −2 −1 0 ]  →  take v = (1, 1, 0):   vTKv = 0 + 0 + 2(−1) = −2  <  0

That says ‖Φ(0) + Φ(1)‖2 = −2, which is impossible for any feature map. So “minus the distance” is not a kernel. The symptom of a fake kernel in practice is an SVM solver that diverges or returns nonsense. The measurement is the smallest eigenvalue of K. The fix is a valid kernel from the lecture’s list below, which fits the same idea of similarity.

Test a similarity on six signals

The six small waves are three pairs: a slow sine, a fast sine and a ramp, each with and without noise. Pick a similarity. Left: its kernel matrix. Right: the eigenvalues of that matrix. Any negative bar means it is not a kernel.

0.70

Toy signals (illustrative): 32 samples each, scaled to length 1, noise from a fixed seed. Passing on six signals does not prove a function is a kernel for all signals. Failing on six proves it is not.

The lecture’s three kernels

Slide 32 lists three kernels, and all pass the test. The homogeneous polynomial kernel is κ(x, y) = (xTy)p. The inhomogeneous polynomial kernel is (1 + xTy)p. Chapter 5 gave the features of both. The third is the one that matters most in practice, the Gaussian kernel, also called the radial basis function (RBF) kernel.

e−‖x−y‖2/(2σ2)
The value is 1 when x = y and falls toward 0 as the points move apart. The width σ sets how far the similarity reaches.

Take σ = 1. Two points at distance 1 get e−0.5 = 0.607. At distance 2 they get e−2 = 0.135. At distance 3 they get e−4.5 = 0.011. Nearby points count a lot, far points almost nothing. This matches the lecture’s reading of a kernel as a measure of similarity.

The Gaussian kernel has endless features

Where is its feature map? Expand the squared distance: ‖x − y‖2 = ‖x‖2 + ‖y‖2 − 2xTy. The exponential of a sum is a product, so the kernel splits into three factors.

κ(x, y) = e−‖x‖²/2σ² · e−‖y‖²/2σ² · exTy/σ²,   and   exTy/σ² = Σk=0∞ (xTy)k / (σ2k k!)

The first two factors each depend on one point only, so they just scale the features. The sum is a polynomial kernel of every degree k, each with a positive weight. By Chapter 5 each degree brings its own monomial features. Together the Gaussian kernel has monomials of all degrees: infinitely many features. That is the lecture’s remark that a kernel can be computed efficiently even if Φ(x) is infinite dimensional. We cannot store such a Φ, but one exponential gives us its dot product.

A similarity function gives a kernel matrix with eigenvalues 3.2, 1.1, 0.4 and −0.2. What do you conclude?

Chapter 7

The Kernel Trick

Swap every dot product in a linear method for a kernel, and train a curved SVM with the same solver

You now hold two facts. Chapter 0 showed that the dual SVM touches the data only through dot products. Chapters 4 to 6 showed that a kernel is a dot product in a lifted space, and that we can compute it without lifting. Put them together and you get the idea the whole lecture is named for.

The recipe

The lecture states the kernel trick as three steps.

  1. Select an inner product kernel κ(x, x′), such as the Gaussian or a polynomial.
  2. Formulate a linear learning method that depends on the data only through inner products ⟨x, x′⟩. The dual SVM is one.
  3. Replace every ⟨x, x′⟩ with κ(x, x′).

Nothing else changes. The solver, the constraints and the objective stay the same. You trained a linear method, but every dot product secretly became a dot product in a lifted space. The method now draws a flat cut up there, which is a curve down here.

Write the dual in matrix form

To see the swap clearly, pack the dual into matrices. Stack the n data points as the rows of a matrix X with n rows and d columns. Then X XT is an n by n table whose entry (i, j) is xiTxj. Let Diag(y) be the n by n matrix with the labels on its diagonal. The double sum Σij αiαjyiyjxiTxj is then αT Diag(y) X XT Diag(y) α. The lecture writes the problem this way.

−½ αT Diag(y) … Diag(y) α
The same pairwise reward as before, in matrix form. Diag(y) attaches each label to its weight.
X XT
The n by n table of dot products between data points. The number of features d vanished here: only n is left.
Σ αi
The reward for using weight.
αTy = 0, 0 ≤ αi ≤ C/n
Balanced classes, and a cap on every weight.
X XT → K
The trick. Replace the table of dot products with the kernel matrix K, whose entries are kernel values.

Look at the shapes. The solver sees only n by n tables. It never sees d, and it never sees the lifted dimension M. That is why a kernel SVM costs the same whether the lifted space has 5 features or infinitely many.

A full example you can check by hand

Take four XOR corners. The same-sign corners are class +1: x1 = (1, 1) and x2 = (−1, −1). The mixed-sign corners are class −1: x3 = (1, −1) and x4 = (−1, 1). No line separates them. Use the kernel κ(x, y) = (xTy)².

  1. Build K. κ(x1, x1) = 2² = 4. κ(x1, x2) = (−2)² = 4. κ(x1, x3) = 0² = 0, and the same for x4. So K has two blocks of 4s, and zeros between the classes.
  2. See the lifted picture. The map Φ(x) = (x1², √2 x1x2, x2²) sends both +1 points to (1, √2, 1) and both −1 points to (1, −√2, 1). Only two lifted points remain, a distance of 2√2 apart.
  3. Use Chapter 1. D = (2√2)² = 8, so γ* = 2/D = 0.25. By symmetry all four weights are equal: αi = 0.125, so each class carries total weight 0.25.
  4. Check the dual value. The vector u = yα = (0.125, 0.125, −0.125, −0.125) gives uTKu = 0.25 + 0.25 = 0.5. The objective is −0.5/2 + Σαi = −0.25 + 0.5 = 0.25, which equals 2/D.
  5. Find the bias. Every point sits on its street edge, and by symmetry b = 0.

We never wrote w, and never needed to. Chapter 8 uses these four weights to classify a new point.

Swap the dot product, train the SVM

The solver is the same each time. Only the kernel changes. Start with the dot product, then try the others. Ringed points are support vectors. The small square is the kernel matrix K, sorted by class.

100
0.80

Toy data (illustrative): 40 noise-free points from a fixed seed. The solver is a small SMO routine on the dual of slide 38, with the box 0 ≤ αi ≤ C/n. The map shades how far each spot is from the boundary.

The failure, and the cure

Start with the dot product on Rings. The symptom is a map cut by a single straight line, with many points wrong. The measurement is the accuracy in the read-out. The cure is one click: choose the Gaussian kernel, and the same solver draws a closed curve around the blob. The data did not change. Only the number that fills the kernel matrix changed.

In the kernel trick, what is replaced, and by what?

Chapter 8

The Kernel Machine

Predict a new point as a weighted vote of the support vectors, and tune the two knobs that decide if it generalizes

The SVM is trained. The solver handed back one weight αi for each training point, and a bias. A new reading arrives from the sensor. How do you label it? You never built the lifted weights w, so you cannot compute wTΦ(x). The last three slides of the lecture show that you do not need to.

The weights are a mix of the lifted data

Chapter 0 gave the rule w* = Σi αi* yixi. The best weights are a signed mix of the data points. The lecture’s first move is a small one: the rule holds in any space where the SVM runs. After lifting each point x to Φ(x), the SVM trained there has w* = Σi αi* yiΦ(xi). The vector w* lives in the lifted space, and we never write it down.

The lecture also writes the line as sign(xTw + b) = sign(x̃Tw̃). Here x̃ is x with a 1 glued on the end, and w̃ is w with b glued on. This only hides the bias inside the weights, so one symbol covers both. Our device keeps b as its own number, which is the usual bookkeeping when the constraint αTy = 0 is in force.

Classify a new point with kernels alone

Take a new point x. Lift it to Φ(x), and take the dot product with w*. Then slide Φ(x) inside the sum, which is allowed because a dot product distributes over a sum.

sign( Φ(x)T w* )
The class of a new point in the lifted space: which side of the flat cut it falls on.
Σ αi* yi Φ(x)TΦ(xi)
The same, after replacing w* by its mix. Each training point contributes its weight, its label, and a dot product with the new point.
Σ αi* yi κ(x, xi)
The lifted dot product is a kernel value. This is the decision rule of the kernel machine. No Φ appears.

Read it as a vote. Each training point i casts a vote of size αiyi. Its sign is the point’s label. The vote is scaled by κ(x, xi), how similar the new point is to point i. Add up all votes, add the bias, and take the sign. Points with αi = 0 cast no vote, so only the support vectors count.

Now the shapes. The new point x has d numbers. The kernel gives a list of n similarities, one per training point. The list α ∘ y has n numbers too. Their dot product is one number. To predict you need only the support vectors and their weights, not the whole training set.

The XOR example, finished

Chapter 7 found αi = 0.125 and b = 0 for the four XOR corners, with κ(x, y) = (xTy)². Classify the new point x = (0.5, 2). Its kernel values are κ(x, x1) = (0.5 + 2)² = 6.25, then κ(x, x2) = (−0.5 − 2)² = 6.25, then κ(x, x3) = (0.5 − 2)² = 2.25, then κ(x, x4) = (−0.5 + 2)² = 2.25.

The votes are 0.125 × (+1) × 6.25 = +0.78 twice, and 0.125 × (−1) × 2.25 = −0.28 twice. The total is 1.56 − 0.56 = 1.00. The sign is positive, so the new point is a same-sign corner. And x1x2 = 0.5 × 2 = 1.0, the same number. The sum collapses to f(x) = x1x2 for every x.

Watch the support vectors vote

Drag the teal probe, or use the sliders. Each line is one vote, and its thickness is the size of the vote. Warm lines vote for class +1, blue lines vote for −1.

0.50
2.00

Exact numbers from Chapter 7: κ = (x·y)², αi = 0.125 on all four corners, b = 0. The shading is the sum of the votes, which simplifies to x₁x₂.

Two knobs decide if it generalizes

A kernel machine has two main knobs. One is C, the price of slack. The other, for the Gaussian kernel, is the width σ. Both can make the machine memorize noise. The symptom is a machine that is perfect on its training points and weak on new ones. The measurement is the gap between training accuracy and accuracy on fresh points. The fix is to move the knob back.

Think of what σ does to the vote. A small σ makes κ(x, xi) near 0 except right on top of xi. Every training point becomes its own tiny island. The kernel matrix looks like the identity, every point is a support vector, and the boundary hugs each point. A large σ makes every kernel value near 1, the votes blur into one, and the boundary flattens toward a straight line. A good σ sits between, at the scale of the gap between the classes.

Tune the knobs, then check fresh data

Noisy rings: the classes overlap a little. Filled dots are training points, small hollow dots are 300 fresh points the machine never saw. The curves show both accuracies for every width at your C.

1.00
100

Toy data (illustrative): 50 training and 300 fresh points from the same noisy rings, fixed seeds, radial noise 0.5. The width slider is logarithmic. Accuracy on fresh points is a sample, so small differences are noise.

Slide the width to its smallest value. Training accuracy climbs to 100% while fresh accuracy falls. That gap is the memorizing. Slide to the largest value and both fall together, which is underfitting. The best fresh accuracy lives in the middle. The same story holds for C: a huge C punishes every crossing and chases the noisy points.

A Gaussian-kernel SVM scores 100% on its training points but 68% on fresh ones, and nearly every point is a support vector. What is the likely cause, and what is the fix?

Chapter 9

Field Guide

Keep the numbers, the checklist and the core code of the lecture on one page

The lecture has one move, told in six steps. A straight cut fails on curved data. A lift turns the curve into a flat cut. The SVM needs only dot products. A kernel gives the lifted dot product without the lift. A function is a kernel when its matrix is positive semidefinite. The trained machine classifies by a vote of support vectors weighted by kernel similarity.

The numbers and terms

IdeaThe rule or the numberChapter
Soft margin SVMmin ½‖w‖² + C(1/n)Σsi, with yi(wTxi + b) ≥ 1 − si0
Dual SVM0 ≤ αi ≤ C/n, Σαiyi = 0, w* = Σαi*yixi0
Hard margin as geometrythe minimum distance between two convex hulls; γ* = 2/D. Example: D = 4 gives w* = (1, 0), b = −21
Multi-class SVMone score wkTx + bk per class, the true class leads by 1 − si2
Binary shortcutsone vs all trains K SVMs, one vs one trains K(K−1)/2. For K = 10: 10 and 452
Circle as a liftΦ(x) = (x1, x2, x1x2, x1², x2²), w = (−2c1, −2c2, 0, 1, 1)3
Energy detectorthreshold on Σxi². For N = 64, σ2² = 2: 88.73
Kernel functionκ(x, x′) = ⟨Φ(x), Φ(x′)⟩. For (xTy)²: d + d(d−1)/2 features, 307,720 at d = 7844
Polynomial kernels(xTy)p has C(d+p−1, p) features; (1 + xTy)p has C(d+p, p). At d = 784, p = 3: 80,622,6405
Valid kernelKij = κ(xi, xj) symmetric positive semidefinite for all points: vTKv ≥ 0, all eigenvalues ≥ 06
Gaussian kernele−‖x−y‖²/2σ², infinitely many features. At σ = 1: 0.607, 0.135, 0.011 at distances 1, 2, 36
Kernel trickreplace X XT with K. The solver sees n × n numbers, never d7
Kernel machineclass = sign(Σαi* yi κ(x, xi)); only support vectors vote8

The checklist

  1. Find the inner products. Does the linear method touch the data only through xTx′? If yes, a kernel can replace it.
  2. Choose a kernel from the list, or test your own with the eigenvalues of its kernel matrix on a sample of points.
  3. Size the bill. The kernel matrix has n × n entries. Compare that with the lifted dimension M times n. This is our practical note, not the slide’s.
  4. Tune on fresh data. Choose C, and σ for the Gaussian kernel, by accuracy on points the machine never trained on.
  5. Predict from support vectors only. Store the points with αi > 0, their labels, their weights and the bias.

The core as code

The whole lecture fits in about 40 lines. The page you played with runs the same routine in JavaScript. The solver gets only the n by n kernel matrix K, and prediction uses only the support vectors.

pythonimport numpy as np

def rbf(A, B, sigma):
    # A: (n, d), B: (m, d)  ->  (n, m) table of kernel values
    d2 = (A**2).sum(1)[:, None] + (B**2).sum(1)[None, :] - 2 * A @ B.T
    return np.exp(-d2 / (2 * sigma**2))

def train_kernel_svm(X, y, sigma=1.0, C=100.0, tol=1e-3, max_passes=6, seed=0):
    # X: (n, d) points, y: (n,) labels in {-1, +1}. Solves the dual of slide 38 with SMO.
    n = len(y)
    K = rbf(X, X, sigma)                      # (n, n): the only thing the solver sees
    box = C / n                               # cap on every alpha
    alpha, b, passes = np.zeros(n), 0.0, 0
    rng = np.random.default_rng(seed)
    f = lambda i: (alpha * y) @ K[:, i] + b   # decision value of training point i
    while passes < max_passes:
        changed = 0
        for i in range(n):
            Ei = f(i) - y[i]
            if (y[i] * Ei < -tol and alpha[i] < box) or (y[i] * Ei > tol and alpha[i] > 0):
                j = rng.choice([k for k in range(n) if k != i])
                Ej, ai, aj = f(j) - y[j], alpha[i], alpha[j]
                if y[i] != y[j]:
                    L, H = max(0, aj - ai), min(box, box + aj - ai)
                else:
                    L, H = max(0, ai + aj - box), min(box, ai + aj)
                eta = 2 * K[i, j] - K[i, i] - K[j, j]
                if L >= H or eta >= 0:
                    continue
                aj_new = np.clip(aj - y[j] * (Ei - Ej) / eta, L, H)
                if abs(aj_new - aj) < 1e-5:
                    continue
                ai_new = ai + y[i] * y[j] * (aj - aj_new)
                b1 = b - Ei - y[i] * (ai_new - ai) * K[i, i] - y[j] * (aj_new - aj) * K[i, j]
                b2 = b - Ej - y[i] * (ai_new - ai) * K[i, j] - y[j] * (aj_new - aj) * K[j, j]
                alpha[i], alpha[j] = ai_new, aj_new
                b = b1 if 0 < ai_new < box else b2 if 0 < aj_new < box else (b1 + b2) / 2
                changed += 1
        passes = passes + 1 if changed == 0 else 0
    return alpha, b

def predict(Xnew, X, y, alpha, b, sigma):
    sv = alpha > 1e-7                         # only the support vectors vote
    return np.sign(rbf(Xnew, X[sv], sigma) @ (alpha[sv] * y[sv]) + b)   # (m, s) @ (s,) -> (m,)

Where it sits, and where to go next

Kernels let a linear method draw curves, at the price of an n by n table. The SVM is one such method. The next lesson uses kernels for regression and builds the feature space (the RKHS) that Mercer’s theorem promises. Earlier lessons behind this one are the support vector machine, convex duality, the Bayes classifier behind the energy detector, and Fisher’s linear discriminant, another linear rule. Least squares comes in the regression lesson.

Credit. This lesson follows Lecture 11 of Stanford EE269, Signal Processing for Machine Learning, taught by Mert Pilanci in Winter 2019. See the course site, the lecture slides and the slide index. The words, the devices and the toy data on this page are ours.

The takeaway. A kernel does not make the data curved. It makes the question flat: the SVM still draws a plane, but the plane lives in a space where dot products are kernel values. Define similarity well, check that its matrix is positive semidefinite, and the same dual solver draws any shape the data need.

Now press Present or Teach and explain from memory three things. Why is a circle a flat cut after a lift? Why does the kernel give the lifted dot product for free? How do the support vectors vote on a new point? Then go back to the plane and cut the rings again.

EE269 Lecture 19: Kernels and Kernel Machines
The course site · Lecture slides · All slides · Back to Gleams