---
title: Kernel methods
heading: Rewriting ridge regression in terms of the data points, kernels as inner products in a feature space you never build, polynomial and Gaussian kernels and when a function is a valid kernel, kernel ridge regression worked by hand, kernel smoothing, and what the dual form costs
eyebrow: S14 · Lesson 32 · Kernel methods
xp: 50
---

::: hook
Lesson 9's basis functions get expensive fast: a cubic in 100 inputs has 176,851 terms. But ridge regression's answer can be rewritten so the features appear only through inner products between pairs of data points, and some inner products of enormous, even infinite, feature vectors can be computed in a few operations straight from the inputs. That's the kernel trick. It turns any linear method that depends only on inner products, ridge regression, PCA, the support vector machine of lesson 33, into a nonlinear one, at a cost that grows with the number of examples instead of the number of features.
:::

::: play
- Kernel smoothing (the Nadaraya–Watson estimator) on five data points: each prediction is a weighted average of the targets, with Gaussian weights $k(x, x_n) = e^{-(x - x_n)^2/2h^2}$.
- A small bandwidth h follows every point; a large one flattens toward the overall mean. It's lesson 9's bias–variance trade with h as the knob.
- Kernel ridge regression uses the same kernel but solves for its weights, which lets it fit the data more closely.
:::

```sim plot
view: graph
x: x = -4..4
y: y = -1.5..2
slider: h = 0.1..3 step 0.05 = 0.6
plot: (-0.5*exp(-(x + 3)^2/(2*h^2)) + 1*exp(-(x + 1.5)^2/(2*h^2)) + 0.4*exp(-x^2/(2*h^2)) + 1.5*exp(-(x - 1)^2/(2*h^2)) - 0.5*exp(-(x - 2.5)^2/(2*h^2)))/(exp(-(x + 3)^2/(2*h^2)) + exp(-(x + 1.5)^2/(2*h^2)) + exp(-x^2/(2*h^2)) + exp(-(x - 1)^2/(2*h^2)) + exp(-(x - 2.5)^2/(2*h^2))) | samples: 600 | label: kernel smoother
point: -3, -0.5
point: -1.5, 1
point: 0, 0.4
point: 1, 1.5
point: 2.5, -0.5
```

::: predict
## The kernel $k(\mathbf{x}, \mathbf{z}) = (\mathbf{x}^T\mathbf{z} + 1)^3$ is used on inputs with 100 components. How many features does it implicitly compute with, and how many operations does one kernel evaluation take?

- [ ] 300 features, 300 operations
- [ ] 1 million features, 1 million operations
- [x] 176,851 features, about 100 operations
- [ ] Infinitely many features, infinitely many operations

::: reveal
$(\mathbf{x}^T\mathbf{z} + 1)^3$ expands into every monomial of degree up to 3, $\binom{103}{3}$ = 176,851 of them (with scale factors). Computing it as written takes one 100-term inner product, an addition and a cube. The Gaussian kernel goes further: its feature space is infinite-dimensional.
:::
:::

::: nameit
## The dual form of ridge regression

Ridge regression's weights can be written as a combination of the training features, $\mathbf{w} = \Phi^T\mathbf{a}$, with

$$\mathbf{a} = (K + \lambda I_N)^{-1}\mathbf{t}, \qquad K_{nm} = k(\mathbf{x}_n, \mathbf{x}_m) = \boldsymbol{\phi}(\mathbf{x}_n)^T\boldsymbol{\phi}(\mathbf{x}_m)$$

and predictions $y(\mathbf{x}) = \sum_na_nk(\mathbf{x}, \mathbf{x}_n)$. The features appear only through the **kernel** k, and K is the N × N **Gram matrix**.

## Kernels

- **Polynomial:** $(\mathbf{x}^T\mathbf{z} + c)^M$, an inner product of all monomials up to degree M: $\binom{D + M}{M}$ features in D dimensions.
- **Gaussian:** $\exp(-\|\mathbf{x} - \mathbf{z}\|^2/2s^2)$, with an infinite feature space; s sets how far each point's influence reaches.

A function is a valid kernel when every Gram matrix it makes is positive semidefinite (Mercer's condition). Sums, products and positive multiples of valid kernels are valid. Distances in feature space follow from the kernel too: $\|\boldsymbol{\phi}(\mathbf{x}) - \boldsymbol{\phi}(\mathbf{z})\|^2 = k(\mathbf{x}, \mathbf{x}) + k(\mathbf{z}, \mathbf{z}) - 2k(\mathbf{x}, \mathbf{z})$.

## Kernel smoothing

The Nadaraya–Watson estimator $y(x) = \sum_nk(x, x_n)t_n/\sum_nk(x, x_n)$ needs no solve at all: a locally weighted average.

## Cost

The primal solve costs about $M^3$ for M features; the dual costs about $N^3$ for N examples and stores $N^2$ kernel values. Kernels win when features vastly outnumber examples and lose when examples number in the millions.
:::

::: example
## Fit kernel ridge regression to the points (0, 1) and (1, 2) with a Gaussian kernel of s = 1 and λ = 0.1, and predict at x = 0.5.

::: solution
1. **Gram matrix.** $k(0, 1) = e^{-1/2}$ = 0.6065, so
   $$K + \lambda I = \begin{bmatrix}1.1 & 0.6065 \\ 0.6065 & 1.1\end{bmatrix}$$
   with determinant
   $$\begin{aligned} \det &= 1.21 - 0.3679 \\ &= 0.8421 \end{aligned}$$
2. **Coefficients.**
   $$\begin{aligned} a_1 &= \frac{1.1 \times 1 - 0.6065 \times 2}{0.8421} \\ &= -0.134 \\ a_2 &= \frac{1.1 \times 2 - 0.6065}{0.8421} \\ &= 1.892 \end{aligned}$$
3. **Predict at x = 0.5.** Both kernels equal $e^{-1/8}$ = 0.8825, so
   $$\begin{aligned} y &= 0.8825 \\ &\quad \times (-0.134 + 1.892) \\ &= 1.551 \end{aligned}$$
4. **At the training points.** The fit gives 1.013 and 1.811, pulled slightly toward each other by λ.

**Answer:** the prediction at x = 0.5 is 1.551.
:::
:::

::: example
## How many features does a quadratic kernel use on 10 inputs, and what does a Gram matrix for 50,000 examples cost to store in double precision?

::: solution
1. **Features.**
   $$\binom{12}{2} = 66$$
   Here the primal form is cheaper.
2. **Gram matrix.** It has $2.5 \times 10^9$ entries, so at 8 bytes each
   $$2.5 \times 10^9 \times 8 = 20\ \text{GB}$$
3. **Solving.** Solving it takes about $10^{14}$ operations, which is why large data sets use approximations.

**Answer:** the quadratic kernel uses 66 features, and the Gram matrix takes 20 GB.
:::
:::

::: example
## Is $k(x, z) = (x - z)^2$ a valid kernel? Test it on the two points 0 and 1, and compare the Gaussian kernel with s = 1 on the same points.

::: solution
1. **What a kernel needs.** A valid kernel must give a positive semidefinite Gram matrix for every set of points.
2. **Test $(x - z)^2$.** Here the Gram matrix is
   $$\begin{bmatrix}0 & 1 \\ 1 & 0\end{bmatrix}$$
   with eigenvalues 1 and −1: the combination (1, −1) would have a negative squared length in feature space, so no feature map exists and the function isn't a kernel.
3. **Gaussian kernel.** It gives
   $$\begin{bmatrix}1 & 0.607 \\ 0.607 & 1\end{bmatrix}$$
   with eigenvalues 1.607 and 0.393, both positive, as they are for any distinct points.
4. **What works.** A distance can't stand in for a similarity; its negative exponential can.

**Answer:** no: $(x - z)^2$ gives a Gram matrix with eigenvalue −1, so it isn't a kernel; the Gaussian kernel's eigenvalues, 1.607 and 0.393, are both positive.
:::
:::

::: check
given: d = 0.5 | 1.5 | 2.5; s = 0.5 | 1 | 2
answer: exp(-d^2/(2*s^2))
tolerance: 0.5%

## Two inputs are {d} apart. What's their Gaussian kernel value with width s = {s}?

::: right
Right. $e^{-d^2/2s^2}$ = {answer}.
:::

::: misses
- [exp(-d/(2*s^2))] Square the distance.
- [any] Not yet. $\exp(-\|\mathbf{x} - \mathbf{z}\|^2/2s^2)$.
:::
:::

::: check
given: a = 1 | 2; b = 0.5 | 1; c = 0.5 | 3; d = 1 | -0.5; M = 2 | 3
answer: (a*c + b*d + 1)^M
tolerance: 0.5%

## What's the polynomial kernel $(\mathbf{x}^T\mathbf{z} + 1)^{\given{M}}$ for x = ({a}, {b}) and z = ({c}, {d})?

::: right
Right. $(\mathbf{x}^T\mathbf{z} + 1)^M$ = {answer}.
:::

::: misses
- [(a*c + b*d)^M] Include the +1, which brings in the lower-degree terms.
- [any] Not yet. Inner product, add 1, raise to the power.
:::
:::

::: check
given: D = 5 | 20 | 60; M = 2 | 3 | 4
answer: (D + M)!/(D!*M!)
tolerance: 0.5%

## How many features does the kernel $(\mathbf{x}^T\mathbf{z} + 1)^{\given{M}}$ correspond to for {D}-component inputs?

::: right
Right. $\binom{D + M}{M}$ = {answer}.
:::

::: misses
- [D^M] Count all monomials up to degree M, without repeats from reordering.
- [any] Not yet. Monomials of degree at most M.
:::
:::

::: check
given: d = 0.5 | 1.5 | 3; s = 1 | 2
answer: 2 - 2*exp(-d^2/(2*s^2))
tolerance: 0.5%

## Two inputs are {d} apart. With a Gaussian kernel of width {s}, what's the squared distance between their feature vectors?

::: right
Right. $k(x, x) + k(z, z) - 2k(x, z) = 2 - 2e^{-d^2/2s^2}$ = {answer}, never more than 2.
:::

::: misses
- [d^2] That's the input-space distance.
- [any] Not yet. Expand $\|\boldsymbol{\phi}(x) - \boldsymbol{\phi}(z)\|^2$ with the kernel.
:::
:::

::: check
given: t = 1 | 3; u = -1 | 2; k = 0.3 | 0.7; l = 0.05 | 0.5
answer: ((1 + l)*t - k*u)/((1 + l)^2 - k^2) + k*((1 + l)*u - k*t)/((1 + l)^2 - k^2)
tolerance: 0.5%

## Kernel ridge regression on two points with targets {t} and {u}, kernel values 1 on the diagonal and {k} between them, and λ = {l}. What does it predict at the first training point?

::: right
Right. $y(x_1) = a_1 + ka_2$ with $\mathbf{a} = (K + \lambda I)^{-1}\mathbf{t}$: {answer}.
:::

::: misses
- [t] With λ > 0 the fit doesn't pass exactly through the targets.
- [any] Not yet. Solve the 2 × 2 system, then $y = \sum a_nk(x_1, x_n)$.
:::
:::

::: check
given: N = 1e4 | 3e4 | 1e5
answer: 8*N^2/1e9
tolerance: 0.5%

## How many gigabytes does the Gram matrix for {N} examples take in double precision (8 bytes per entry)?

::: right
Right. $8N^2$ bytes = {answer} GB.
:::

::: misses
- [8*N/1e9] The Gram matrix has N² entries.
- [any] Not yet. N × N entries of 8 bytes.
:::
:::

::: check
kind: parts
given: d = 0.1 | 0.5 | 1 | 2; s = 0.5 | 1 | 3

## Two training inputs are {d} apart, and a Gaussian kernel of width s = {s} is used.

::: part
answer: 1 - exp(-d^2/(2*s^2))
tolerance: 0.5%

### What is the Gram matrix's smaller eigenvalue?

::: misses
- [exp(-d^2/(2*s^2))] That's the off-diagonal entry; the eigenvalues are 1 ± k.
- [any] $1 - k(x_1, x_2)$.
:::
:::

::: part
answer: (1 + exp(-d^2/(2*s^2)))/(1 - exp(-d^2/(2*s^2)))
tolerance: 0.5%

### What is its condition number?

::: misses
- [any] $(1 + k)/(1 - k)$.
:::
:::
:::

::: check
kind: derivation
vars: k = 0..0.95, l = 0.001..2, t = -3..3, u = -3..3

## Kernel ridge regression uses two training points with targets t and u, a Gram matrix with ones on the diagonal and k off it, and regularization λ.

::: step
answer: ((1 + l)*t - k*u)/((1 + l)^2 - k^2)

### What is the first dual coefficient $a_1$?
:::

::: step
answer: ((1 + l)*u - k*t)/((1 + l)^2 - k^2)

### What is $a_2$?
:::

::: right
Right. As the points become nearly identical (k near 1), the coefficients blow up unless λ holds them down.
:::
:::

::: explain
## How can a kernel compute with infinitely many features at finite cost?

::: model
Many learning algorithms use the features only through inner products between pairs of examples, so it's enough to know those inner products, never the feature vectors themselves. For some feature maps the inner product has a closed form in the original inputs: the polynomial kernel's sum over every monomial collapses into a power of the ordinary inner product, and the Gaussian kernel's infinite series of features sums to a single exponential of the squared distance. The algorithm then works with the N × N matrix of kernel values, whose size depends on the number of examples, while the feature space it effectively uses can be as large as the kernel implies.
:::
:::

::: practice

::: check
given: d = 0.1 | 4; s = 0.3 | 3
answer: exp(-d^2/(2*s^2))
tolerance: 0.5%

## Gaussian kernel: distance {d}, width {s}?

::: misses
- [any] $e^{-d^2/2s^2}$.
:::
:::

::: check
given: D = 2 | 60; M = 1 | 5
answer: (D + M)!/(D!*M!)
tolerance: 0.5%

## Polynomial kernel features: D = {D}, M = {M}?

::: misses
- [any] $\binom{D + M}{M}$.
:::
:::

::: check
given: d = 0.2 | 5; s = 0.5 | 2
answer: 2 - 2*exp(-d^2/(2*s^2))
tolerance: 0.5%

## Feature-space squared distance: d = {d}, s = {s}?

::: misses
- [any] $2 - 2e^{-d^2/2s^2}$.
:::
:::
:::
