Simple Algorithm
Machine Learning · Convergence · 26 min

Feature Maps & the Road to Kernels

Explicit feature expansions, their cost, and random features.

Every nonlinear model in this topic was linear in some features. The trouble is how many: the monomials of degree at most 3 in the 784 pixels of a small image already number about 81 million, and the Gaussian kernel's features are infinitely many. This lesson counts the cost of explicit expansions, shows that learning needs only inner products of features, and then goes back the other way: a few thousand random features approximate an infinite feature map with provable error, form a two-layer network with a frozen first layer, and trace a double-descent curve of their own.

What you’ll learn

  • Count the monomials of an explicit polynomial expansion, (d+pp)\binom{d+p}{p}, and weigh the computational and statistical cost of explicit features.
  • Show that ridge regression on features needs only their inner products, and derive the feature maps behind the polynomial and Gaussian kernels.
  • Derive random Fourier features from Bochner's theorem, and bound their error pointwise with Hoeffding's inequality and uniformly with Rahimi and Recht's theorem.
  • Explain how many random features learning needs, the double descent of random-features regression, and what fixed random features cannot learn efficiently in high dimension.

Explicit feature maps and their cost

A feature map φ:Rd→RM\boldsymbol\varphi:\R^d\to\R^M turns any linear method into a nonlinear one: fit least squares, ridge or logistic regression to φ(x)\boldsymbol\varphi(\mathbf x) instead of x\mathbf x. Lifting data into more dimensions makes linear separation easy. Cover's function-counting theorem (1965) says that nn points in general position in RM\R^M can be split by a hyperplane through the origin in exactly

C(n,M)=2∑k=0M−1(n−1k)C(n,M)=2\sum_{k=0}^{M-1}\binom{n-1}{k}

of the 2n2^n possible ways: all of them when n≤Mn\le M, and exactly half when n=2Mn=2M. With enough features, every labeling is linearly separable, the meaningful ones and the noise alike.

DerivationHow many monomials of degree at most p?
  1. #{α: α1+⋯+αd≤p}=#{(α0,…,αd)≥0: α0+α1+⋯+αd=p}\#\{\boldsymbol\alpha:\ \alpha_1+\dots+\alpha_d\le p\}=\#\{(\alpha_0,\dots,\alpha_d)\ge0:\ \alpha_0+\alpha_1+\dots+\alpha_d=p\}

    A monomial x1α1⋯xdαdx_1^{\alpha_1}\cdots x_d^{\alpha_d} of degree at most pp is a vector of exponents with α1+⋯+αd≤p\alpha_1+\dots+\alpha_d\le p. Add a slack exponent α0=p−∑jαj\alpha_0=p-\sum_j\alpha_j to make the total exactly pp:

  2. M(d,p)=(d+pp)≈dpp!for fixed p and large dM(d,p)=\binom{d+p}{p}\approx\frac{d^p}{p!}\quad\text{for fixed }p\text{ and large }d

    Placing pp identical units into d+1d+1 bins is a stars-and-bars count:

  3. (7873)=80,931,145\binom{787}{3}=80{,}931{,}145

    For a 28×2828\times28 image (d=784d=784) and p=3p=3 that is 80,931,145 features. Ridge regression on MM explicit features costs O(nM2+M3)\order{nM^2+M^3} time, and the variance argument of Basis Functions & Generalized Linear Models charges σ2M/n\sigma^2M/n before any regularization.

Predict before you look

A model uses all monomials of degree at most 3 in d=20d=20 inputs, the constant included. How many features is that?

Show the answer

1771 features

(233)=1,771\binom{23}{3}=1{,}771: 1 constant, 20 linear terms, (212)=210\binom{21}{2}=210 quadratic and (223)=1,540\binom{22}{3}=1{,}540 cubic monomials. With 100 inputs it would be 176,851. Polynomial expansions are affordable only for small dd or small pp.

Learning needs only inner products

Ridge regression on features has a dual form (Ridge Regression in Depth): with Φ\Phi the n×Mn\times M feature matrix,

w^=Φ⊤(ΦΦ⊤+λI)−1y,f^(x)=φ(x)⊤w^=k(x)⊤(K+λI)−1y,\hat{\mathbf w}=\Phi^\top(\Phi\Phi^\top+\lambda I)^{-1}\mathbf y,\qquad\hat f(\mathbf x)=\boldsymbol\varphi(\mathbf x)^\top\hat{\mathbf w}=\mathbf k(\mathbf x)^\top(K+\lambda I)^{-1}\mathbf y,

where Kij=k(xi,xj)K_{ij}=k(\mathbf x_i,\mathbf x_j) and ki(x)=k(xi,x)k_i(\mathbf x)=k(\mathbf x_i,\mathbf x) with k(x,z)=φ(x)⊤φ(z)k(\mathbf x,\mathbf z)=\boldsymbol\varphi(\mathbf x)^\top\boldsymbol\varphi(\mathbf z). The features appear only through their inner products. If kk can be computed without building φ\boldsymbol\varphi, the cost is O(n2)\order{n^2} memory and O(n3)\order{n^3} time whatever MM is, even infinite: the kernel trick. Which functions kk are inner products of some feature map, and why the solution always has this form, are the subjects of Reproducing Kernel Hilbert Spaces.

DerivationThe feature maps behind two kernels
  1. (1+x⊤z)2=1+2x1z1+2x2z2+x12z12+x22z22+2x1x2z1z2(1+\mathbf x^\top\mathbf z)^2=1+2x_1z_1+2x_2z_2+x_1^2z_1^2+x_2^2z_2^2+2x_1x_2z_1z_2

    Expand the degree-2 polynomial kernel in d=2d=2 dimensions:

  2. φ(x)=(1, 2 x1, 2 x2, x12, x22, 2 x1x2)\boldsymbol\varphi(\mathbf x)=\big(1,\ \sqrt2\,x_1,\ \sqrt2\,x_2,\ x_1^2,\ x_2^2,\ \sqrt2\,x_1x_2\big)

    It is the inner product of two explicit six-dimensional feature vectors, one feature per monomial of degree at most 2, which is (2+22)=6\binom{2+2}{2}=6:

  3. φα(x)=p!α0! α1!⋯αd!  x1α1⋯xdαd\varphi_{\boldsymbol\alpha}(\mathbf x)=\sqrt{\frac{p!}{\alpha_0!\,\alpha_1!\cdots\alpha_d!}}\;x_1^{\alpha_1}\cdots x_d^{\alpha_d}

    In general, the multinomial theorem gives (1+x⊤z)p=∑p!α0!α1!⋯αd! xαzα(1+\mathbf x^\top\mathbf z)^p=\sum\frac{p!}{\alpha_0!\alpha_1!\cdots\alpha_d!}\,\mathbf x^{\boldsymbol\alpha}\mathbf z^{\boldsymbol\alpha} over α0+∣α∣=p\alpha_0+\abs{\boldsymbol\alpha}=p: all (d+pp)\binom{d+p}{p} monomials with fixed weights, computed in O(d)\order{d} operations instead of O(dp)\order{d^p}.

  4. e−∥x−z∥2/(2ℓ2)=e−∥x∥2/(2ℓ2) e−∥z∥2/(2ℓ2)∑k=0∞(x⊤z)kℓ2k k!e^{-\norm{\mathbf x-\mathbf z}^2/(2\ell^2)}=e^{-\norm{\mathbf x}^2/(2\ell^2)}\,e^{-\norm{\mathbf z}^2/(2\ell^2)}\sum_{k=0}^\infty\frac{(\mathbf x^\top\mathbf z)^k}{\ell^{2k}\,k!}

    The Gaussian (RBF) kernel factors into a product of normalizations and an exponential of x⊤z\mathbf x^\top\mathbf z, whose Taylor series is a sum of polynomial kernels of every degree: an infinite-dimensional feature map with weights decaying like 1/k!1/k!.

Think first When is it cheaper to build the features explicitly than to use the kernel?

Explicit ridge costs about O(nM2+M3)\order{nM^2+M^3} and the kernel form about O(n2d+n3)\order{n^2d+n^3}. With few features and many examples (M≪nM\ll n, say n=106n=10^6 points and quadratic features of d=10d=10 inputs, M=66M=66), build the features. With many features and few examples, or infinitely many features as for the Gaussian kernel, use the kernel. When both nn and MM are large, neither works, which is the problem random features solve.

Random Fourier features

DerivationA Monte Carlo feature map (Rahimi & Recht, 2007)
  1. 2cos⁡(ω⊤x+b)cos⁡(ω⊤z+b)=cos⁡(ω⊤(x−z))+cos⁡(ω⊤(x+z)+2b)2\cos(\boldsymbol\omega^\top\mathbf x+b)\cos(\boldsymbol\omega^\top\mathbf z+b)=\cos\big(\boldsymbol\omega^\top(\mathbf x-\mathbf z)\big)+\cos\big(\boldsymbol\omega^\top(\mathbf x+\mathbf z)+2b\big)

    Draw ω∼p\boldsymbol\omega\sim p and an independent phase b∼U[0,2π]b\sim\mathrm U[0,2\pi]. The product-to-sum identity splits the product of two cosines:

  2. Eω,b[2cos⁡(ω⊤x+b)cos⁡(ω⊤z+b)]=κ(x−z)\E_{\boldsymbol\omega,b}\big[2\cos(\boldsymbol\omega^\top\mathbf x+b)\cos(\boldsymbol\omega^\top\mathbf z+b)\big]=\kappa(\mathbf x-\mathbf z)

    Averaging over the phase kills the second term, and averaging over ω\boldsymbol\omega turns the first into the kernel, by Bochner:

  3. ψ(x)=2D(cos⁡(ω1⊤x+b1),…,cos⁡(ωD⊤x+bD)),E[ψ(x)⊤ψ(z)]=k(x,z)\boldsymbol\psi(\mathbf x)=\sqrt{\frac2D}\Big(\cos(\boldsymbol\omega_1^\top\mathbf x+b_1),\dots,\cos(\boldsymbol\omega_D^\top\mathbf x+b_D)\Big),\qquad\E\big[\boldsymbol\psi(\mathbf x)^\top\boldsymbol\psi(\mathbf z)\big]=k(\mathbf x,\mathbf z)

    Average DD independent copies. The map ψ(⋅)\boldsymbol\psi(\cdot) below is a DD-dimensional explicit feature map whose inner products are unbiased estimates of the kernel:

  4. e−∥δ∥2/(2ℓ2) ⟷ ω∼N(0, ℓ−2I)e^{-\norm{\boldsymbol\delta}^2/(2\ell^2)}\ \longleftrightarrow\ \boldsymbol\omega\sim\mathcal N(\mathbf 0,\ \ell^{-2}I)

    For the Gaussian kernel the spectral distribution is itself Gaussian; for the Laplacian kernel e−∥δ∥1e^{-\norm{\boldsymbol\delta}_1} it is a product of Cauchy distributions:

How good is the approximation? Each term 2cos⁡(⋅)cos⁡(⋅)2\cos(\cdot)\cos(\cdot) lies in [−2,2][-2,2], so Hoeffding's inequality gives, for each fixed pair of points,

Pr⁡[∣ψ(x)⊤ψ(z)−k(x,z)∣≥ε]≤2exp⁡(−Dε28),\Pr\Big[\big|\boldsymbol\psi(\mathbf x)^\top\boldsymbol\psi(\mathbf z)-k(\mathbf x,\mathbf z)\big|\ge\varepsilon\Big]\le2\exp\Big(-\frac{D\varepsilon^2}8\Big),

an error of order 1/D1/\sqrt D that does not depend on the dimension dd. The error is also small uniformly over a region. Rahimi and Recht's Claim 1 proves this for the paired map ψ~(x)=1/D (cos⁡(ωj⊤x), sin⁡(ωj⊤x))j=1D\tilde{\boldsymbol\psi}(\mathbf x)=\sqrt{1/D}\,\big(\cos(\boldsymbol\omega_j^\top\mathbf x),\ \sin(\boldsymbol\omega_j^\top\mathbf x)\big)_{j=1}^{D} (2D2D features from DD frequencies, the map of their Algorithm 1): for a compact set M⊂Rd\mathcal M\subset\R^d,

Pr⁡[sup⁡x,z∈M∣ψ~(x)⊤ψ~(z)−k(x,z)∣≥ε]≤28(σpdiam⁡(M)ε)2exp⁡(−Dε24(d+2)),σp2=E∥ω∥2.\Pr\Big[\sup_{\mathbf x,\mathbf z\in\mathcal M}\big|\tilde{\boldsymbol\psi}(\mathbf x)^\top\tilde{\boldsymbol\psi}(\mathbf z)-k(\mathbf x,\mathbf z)\big|\ge\varepsilon\Big]\le2^8\Big(\frac{\sigma_p\operatorname{diam}(\mathcal M)}\varepsilon\Big)^2\exp\Big(-\frac{D\varepsilon^2}{4(d+2)}\Big),\qquad\sigma_p^2=\E\norm{\boldsymbol\omega}^2.

For the random-phase map ψ\boldsymbol\psi above, Sutherland and Schneider (2015) prove a bound of the same form with larger constants. Either way, DD of order (d/ε2)log⁡(σpdiam⁡(M)/ε)(d/\varepsilon^2)\log(\sigma_p\operatorname{diam}(\mathcal M)/\varepsilon) features give uniform error ε\varepsilon with constant probability. Using the pair cos⁡(ω⊤x),sin⁡(ω⊤x)\cos(\boldsymbol\omega^\top\mathbf x),\sin(\boldsymbol\omega^\top\mathbf x) instead of a random phase removes the second term of the identity above, and for the Gaussian kernel this has lower variance even for the same total number of features.

Predict before you look

Using the pointwise Hoeffding bound 2e−Dε2/8≤δ2e^{-D\varepsilon^2/8}\le\delta, how many random features guarantee error at most ε=0.05\varepsilon=0.05 for a given pair of points with probability at least 0.990.99?

Show the answer

16955 features

D≥8ln⁡(2/δ)/ε2=8ln⁡200/0.0025≈16,955D\ge8\ln(2/\delta)/\varepsilon^2=8\ln200/0.0025\approx16{,}955. Accurate kernel approximation is expensive because Monte Carlo error falls only like 1/D1/\sqrt D. Learning turns out to need far fewer features than approximating the kernel this accurately, as the next step shows.

python
import numpy as np

def rff(X, D, lengthscale, rng):
    """Random Fourier features for k(x, z) = exp(-||x - z||^2 / (2 l^2))."""
    W = rng.normal(scale=1.0 / lengthscale, size=(X.shape[1], D))   # omega ~ N(0, I / l^2)
    b = rng.uniform(0.0, 2 * np.pi, size=D)                         # random phases
    return lambda A: np.sqrt(2.0 / D) * np.cos(A @ W + b)

rng = np.random.default_rng(0)
phi = rff(X_train, D=2000, lengthscale=1.0, rng=rng)
Z = phi(X_train)                         # n x D features instead of an n x n Gram matrix
lam = 0.1
w = np.linalg.solve(Z.T @ Z + lam * np.eye(Z.shape[1]), Z.T @ y_train)   # O(n D^2 + D^3)
y_pred = phi(X_test) @ w                 # approximates kernel ridge regression

Ridge regression on random Fourier features. scikit-learn's RBFSampler(gamma, n_components) builds the same features for the kernel e−γ∥x−z∥2e^{-\gamma\norm{\mathbf x-\mathbf z}^2}, that is γ=1/(2ℓ2)\gamma=1/(2\ell^2).

How many features does learning need?

Approximating the kernel to accuracy ε\varepsilon everywhere is more than learning requires. Rudi & Rosasco (2017) showed that ridge regression with about nlog⁡n\sqrt n\log n random features already attains the O(1/n)\order{1/\sqrt n} learning bound of exact kernel ridge regression in the basic setting; faster rates can need more features, unless the features are sampled from a problem-dependent distribution. The cost drops from O(n3)\order{n^3} for exact kernel ridge regression to O(nD2)=O(n2log⁡2n)\order{nD^2}=\order{n^2\log^2n}, and the memory from n2n^2 to nDnD. Scaling Kernel Methods compares this with the Nyström method.

Random features are also a neural network: with NN features (the DD above, in the notation of the double-descent literature), f^(x)=∑j=1Naj σ(ωj⊤x+bj)\hat f(\mathbf x)=\sum_{j=1}^Na_j\,\sigma(\boldsymbol\omega_j^\top\mathbf x+b_j) is a two-layer network whose first layer is random and frozen, with σ=cos⁡\sigma=\cos here or a ReLU in other versions, and only the output weights aja_j trained. That makes it the simplest model in which to study overparameterization exactly.

What random features cannot do. Fixed features pay for not adapting to the target. Ghorbani, Mei, Misiakiewicz & Montanari (2021) studied inputs uniform on a high-dimensional sphere: with NN features between dℓ+δd^{\ell+\delta} and dℓ+1−δd^{\ell+1-\delta} (and unlimited data), a random-features model can effectively fit only polynomials of degree ℓ\ell in the inputs; with unlimited features, kernel methods trained on nn samples in the same range fit at most degree-ℓ\ell polynomials. Even a cubic function of a single direction, (θ⊤x)3(\boldsymbol\theta^\top\mathbf x)^3, then needs of order d3d^3 random features or samples. Networks that train their first layer can, in principle, align their features with the relevant direction, one theoretical account of why learned features beat fixed ones (Infinite Width: NTK & Mean-Field Limits).

Key takeaways

  • There are (d+pp)≈dp/p!\binom{d+p}{p}\approx d^p/p! monomials of degree at most pp in dd variables, about 81 million cubic features for a 28×2828\times28 image; by Cover's count, enough features make any labeling separable.
  • Ridge on features needs only inner products: f^(x)=k(x)⊤(K+λI)−1y\hat f(\mathbf x)=\mathbf k(\mathbf x)^\top(K+\lambda I)^{-1}\mathbf y. (1+x⊤z)p(1+\mathbf x^\top\mathbf z)^p is an inner product of weighted monomials computed in O(d)\order{d}, and the Gaussian kernel's feature map is infinite.
  • Bochner: shift-invariant positive definite kernels are expectations Eωcos⁡(ω⊤(x−z))\E_{\boldsymbol\omega}\cos(\boldsymbol\omega^\top(\mathbf x-\mathbf z)); 2/Dcos⁡(ωj⊤x+bj)\sqrt{2/D}\cos(\boldsymbol\omega_j^\top\mathbf x+b_j) gives unbiased random features with error O(1/D)\order{1/\sqrt D}, uniformly over compact sets with D≈(d/ε2)log⁡(1/ε)D\approx(d/\varepsilon^2)\log(1/\varepsilon).
  • Learning needs fewer features than approximation: about nlog⁡n\sqrt n\log n match kernel ridge regression's basic O(1/n)\order{1/\sqrt n} bound at cost O(nD2)\order{nD^2}.
  • Random features are two-layer networks with a frozen first layer; their minimum-norm fit shows double descent with a peak at N=nN=n, and in high dimension they need about dℓd^\ell features to fit degree-ℓ\ell polynomials.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

How many monomials of degree at most 3 are there in d=100d=100 variables, the constant included?

  1. 5,151
  2. 176,851
  3. 1,000,000
  4. 161,700
Show the answer

B. 176,851

(1033)=176,851\binom{103}{3}=176{,}851. The count grows like d3/6d^3/6, so a cubic expansion of a few hundred inputs is already out of reach, while the cubic polynomial kernel (1+x⊤z)3(1+\mathbf x^\top\mathbf z)^3 costs O(d)\order{d} per evaluation.

Question 2

What does Bochner's theorem say about a continuous shift-invariant function κ(x−z)\kappa(\mathbf x-\mathbf z)?

  1. It is a positive definite kernel if and only if κ\kappa is the Fourier transform of a nonnegative measure
  2. Every such function is a valid kernel
  3. It is a positive definite kernel if and only if κ≥0\kappa\ge0 everywhere
  4. Only the Gaussian kernel can be approximated by random features
Show the answer

A. It is a positive definite kernel if and only if κ\kappa is the Fourier transform of a nonnegative measure

Positive definiteness of a shift-invariant kernel is equivalent to a nonnegative spectrum. Normalized, that spectrum is a probability distribution, and sampling frequencies from it gives random Fourier features for any such kernel: Gaussian, Laplacian, Cauchy, Matérn.

Question 3

Why do random Fourier features use cos⁡(ω⊤x+b)\cos(\boldsymbol\omega^\top\mathbf x+b) with a uniformly random phase bb?

  1. So that the features are nonnegative
  2. To center the data before the projection
  3. So that the cross term cos⁡(ω⊤(x+z)+2b)\cos(\boldsymbol\omega^\top(\mathbf x+\mathbf z)+2b) averages to zero, making the inner product an unbiased estimate of κ(x−z)\kappa(\mathbf x-\mathbf z)
  4. To make the features bounded
Show the answer

C. So that the cross term cos⁡(ω⊤(x+z)+2b)\cos(\boldsymbol\omega^\top(\mathbf x+\mathbf z)+2b) averages to zero, making the inner product an unbiased estimate of κ(x−z)\kappa(\mathbf x-\mathbf z)

2cos⁡(ω⊤x+b)cos⁡(ω⊤z+b)=cos⁡(ω⊤(x−z))+cos⁡(ω⊤(x+z)+2b)2\cos(\boldsymbol\omega^\top\mathbf x+b)\cos(\boldsymbol\omega^\top\mathbf z+b)=\cos(\boldsymbol\omega^\top(\mathbf x-\mathbf z))+\cos(\boldsymbol\omega^\top(\mathbf x+\mathbf z)+2b). Only the first term depends on x−z\mathbf x-\mathbf z; the uniform phase makes the second vanish on average. Using both cos⁡\cos and sin⁡\sin of ω⊤x\boldsymbol\omega^\top\mathbf x removes it exactly.

Question 4

With n=106n=10^6 training examples, roughly how expensive is exact kernel ridge regression compared with ridge regression on D=104D=10^4 random features?

  1. About the same: both scale with n3n^3
  2. Random features are more expensive because DD is large
  3. Exact: about nD=1010nD=10^{10} operations; random features: about n2=1012n^2=10^{12}
  4. Exact: about n3=1018n^3=10^{18} operations and n2=1012n^2=10^{12} stored entries; random features: about nD2=1014nD^2=10^{14} operations and nD=1010nD=10^{10} entries
Show the answer

D. Exact: about n3=1018n^3=10^{18} operations and n2=1012n^2=10^{12} stored entries; random features: about nD2=1014nD^2=10^{14} operations and nD=1010nD=10^{10} entries

Kernel ridge regression builds and solves an n×nn\times n system. With DD features, forming Z⊤ZZ^\top Z costs nD2nD^2 and solving it D3=1012D^3=10^{12}, so the total is about 101410^{14}: ten thousand times cheaper, and the n×Dn\times D feature matrix fits where an n×nn\times n Gram matrix would not.

Further reading

  • A. Rahimi & B. Recht, "Random features for large-scale kernel machines," NeurIPS (2007).
  • D. J. Sutherland & J. Schneider, "On the error of random Fourier features," UAI (2015).
  • T. M. Cover, "Geometrical and statistical properties of systems of linear inequalities with applications in pattern recognition," IEEE Transactions on Electronic Computers EC-14, 326–334 (1965).
  • A. Rudi & L. Rosasco, "Generalization properties of learning with random features," NeurIPS (2017).
  • S. Mei & A. Montanari, "The generalization error of random features regression: precise asymptotics and the double descent curve," Communications on Pure and Applied Mathematics 75(4), 667–766 (2022).
  • B. Schölkopf & A. J. Smola, Learning with Kernels (MIT Press, 2002).