Core ML2007intermediate12 min read

Random Features for Large-Scale Kernel Machines

السِّمات العشوائية لآلات النواة واسعة النِّطاق

Rahimi, A. · Recht, B. — NeurIPS

The problem

Kernel methods like SVMs learn nonlinear decision boundaries by implicitly mapping data into a high-dimensional (even infinite) via the . But the kernel matrix grows as N×N with size, making storage and computation prohibitive for datasets with hundreds of thousands of points. By 2007, training an SVM on half a million examples could take days.

The contribution

Instead of using the kernel trick implicitly, map data explicitly into a low-dimensional randomized feature space z(x) ∈ ℝᴰ so that z(x)ᵀz(y) ≈ k(x,y). Two such maps are proposed: (cosines sampled from the kernel's spectral ) for smooth interpolation kernels, and Random Binning Features (randomly shifted grids) for L1-based kernels. Both come with uniform guarantees. After the transform, any fast linear learner can be used, achieving accuracy comparable to exact kernel machines at a fraction of the cost.

The impact

Random Fourier Features became one of the most cited tools in scalable kernel methods and directly inspired the theoretical framework connecting kernels to neural networks — the Neural Tangent Kernel. The paper won the NeurIPS Test of Time Award in 2017 and opened the door to applying kernel-quality nonlinear learning at scales previously reserved for linear methods.

Imagine a detective who must compare every pair of fingerprints in a city of a million people — that's a trillion comparisons. Kernel machines face the same explosion: to learn complex patterns they must compare every training example against every other.

Random Features offer a shortcut stamp pad: instead of comparing raw fingerprints, each person presses their finger onto a special ink pad that captures just a few random strokes. Two stamps that look similar mean the originals were similar too — but now comparisons take microseconds instead of minutes.

The mathematical ink pad is a set of random cosine functions. The surprising result: a few hundred random strokes approximate the full fingerprint match almost perfectly.

The bottleneck: kernel machines don't scale

Support Machines and other kernel methods are powerful because they can learn any decision boundary, given enough data. The kernel trick lets you work in a potentially infinite-dimensional feature space without ever computing the coordinates — you only need the between every pair of points, packaged in a kernel matrix KK where Kij=k(xi,xj)K_{ij} = k(x_i, x_j).

The catch: that matrix has N2N^2 entries. Storing it for N=500,000N = 500{,}000 takes about 1 TB of RAM; computing it takes O(N2d)O(N^2 d) time. Decomposition solvers like SMO or SVMlight nibble at this matrix iteratively, but they still don't scale past a few hundred thousand points. Meanwhile, linear SVMs — which simply find a hyperplane w⊤x+b=0w^\top x + b = 0 — run in O(Nd)O(Nd) time, but they can only draw straight decision boundaries.

The question this paper asks: can we get kernel-quality nonlinearity at linear-method speed?

Open in Lab
Drag the slider to grow N. Watch the kernel matrix (left) explode while the random feature matrix (right) stays slim.
The demo wakes as you arrive…

The core idea: approximate the kernel with random projections

The kernel trick says k(x,y)=⟨ϕ(x),ϕ(y)⟩k(x, y) = \langle \phi(x), \phi(y) \rangle for some (often infinite-dimensional) lifting ϕ\phi. Rahimi and Recht flip this: instead of working implicitly in the huge ϕ\phi-space, build a short explicit map z:Rd→RDz: \mathbb{R}^d \to \mathbb{R}^D (with D≪ND \ll N) so that:

k(x,y)≈z(x)⊤z(y)k(x, y) \approx z(x)^\top z(y)

Once every training point is transformed to z(xi)z(x_i), you store an N×DN \times D matrix instead of N×NN \times N. Any linear learner — ridge , linear SVM, logistic regression — now solves the problem in O(ND2)O(ND^2) time rather than O(N2d)O(N^2 d).

The key insight is that for shift-invariant kernels — kernels that depend only on the difference x−yx - y, such as the Gaussian RBF — Bochner's theorem from harmonic analysis tells us exactly how to build zz.

Bochner's theorem and Random Fourier Features

A depends only on the displacement: k(x,y)=k(x−y)k(x, y) = k(x - y). Bochner's theorem (1933) says that any such continuous positive-definite kernel is the Fourier transform of a non-negative measure. If kk is properly scaled so that k(0)=1k(0) = 1, its Fourier transform p(ω)p(\omega) is a proper distribution.

This means we can write the kernel as an expectation:

k(x−y)=Eω∼p[ejω⊤(x−y)]k(x - y) = \mathbb{E}_{\omega \sim p}\left[ e^{j\omega^\top(x-y)} \right]

Since both p(ω)p(\omega) and kk are real, the imaginary parts cancel, and we can replace the complex exponential with a cosine. Drawing ω\omega from pp and bb uniformly from [0,2π][0, 2\pi], the scalar function zω(x)=2cos⁡(ω⊤x+b)z_\omega(x) = \sqrt{2}\cos(\omega^\top x + b) satisfies:

E[zω(x) zω(y)]=k(x−y)\mathbb{E}[z_\omega(x)\, z_\omega(y)] = k(x - y)

Each random cosine is an unbiased estimator of the kernel evaluation. Stack DD of them into a vector, normalize by D\sqrt{D}, and the inner product z(x)⊤z(y)z(x)^\top z(y) becomes a low- approximation. Hoeffding's inequality guarantees exponentially fast convergence in DD.

z(x)=2D[cos⁡(ω1⊤x+b1)    ⋯    cos⁡(ωD⊤x+bD)]⊤z(x) = \sqrt{\tfrac{2}{D}} \Big[\cos(\omega_1^\top x + b_1) \;\;\cdots\;\; \cos(\omega_D^\top x + b_D)\Big]^\top
Random Fourier Feature map — Each frequency vector omega_j is sampled from p(omega), the Fourier transform of the kernel. Each phase offset b_j is sampled uniformly between 0 and 2*pi. The dot product between z(x) and z(y) approximates the kernel value k(x - y).

Think of it as a frequency scanner: each random cosine projects the input onto a randomly chosen line in the data space, then wraps that projection onto a circle. Two points that land near each other on many circles must have been close in the original kernel sense — the same way two radio stations that produce similar readings on many randomly tuned receivers must be broadcasting similar signals.

Open in Lab
Each row is a random cosine projection. Watch how adding more features (D) makes the approximated kernel matrix converge to the true Gaussian RBF kernel.
The demo wakes as you arrive…

Kernel ↔ spectral distribution: the recipe

Bochner's theorem tells us that every shift-invariant kernel has a spectral distribution p(ω)p(\omega). The choice of kernel determines where the random frequencies ω\omega come from:

  • Gaussian RBF k(Δ)=exp⁡(−∥Δ∥2/2)k(\Delta) = \exp(-\|\Delta\|^2 / 2): draw ω\omega from a Gaussian N(0,I)\mathcal{N}(0, I).
  • Laplacian k(Δ)=exp⁡(−∥Δ∥1)k(\Delta) = \exp(-\|\Delta\|_1): draw each ωd\omega_d from a Cauchy distribution 1π(1+ωd2)\frac{1}{\pi(1 + \omega_d^2)}.
  • Cauchy kernel k(Δ)=∏d21+Δd2k(\Delta) = \prod_d \frac{2}{1 + \Delta_d^2}: draw ω\omega from a Laplacian (double-exponential) e−∥ω∥1e^{-\|\omega\|_1}.

The pattern is elegant: kernels and their spectral distributions are Fourier duals. A narrow kernel (local influence) has a wide spectral distribution, and vice versa — exactly the uncertainty principle from signal processing.

Open in Lab
Pick a kernel to see its shape (left) and spectral distribution (right). A narrow kernel produces a wide spectrum, and vice versa.
The demo wakes as you arrive…

The second weapon: Random Binning Features

Not all kernels are smooth. The Laplacian kernel e−∣x−y∣e^{-|x-y|} and other L1-based kernels have sharp corners. For these, Rahimi and Recht propose a second map: Random Binning Features.

The idea is beautifully spatial: partition the input space with a randomly shifted grid at a randomly chosen resolution. Each point is encoded as a binary indicator vector marking which bin it lands in. If two points fall in the same bin, their is 1; otherwise 0. The grid resolution is sampled from a distribution derived from the kernel, so the probability of co-binning equals the kernel value: Pr⁡[x^=y^]=k(x,y)\Pr[\hat{x} = \hat{y}] = k(x, y).

Stack PP independent random binnings and average — you get a low-variance, unbiased estimator of the kernel. Unlike Fourier features, binning is piecewise constant — it explicitly preserves locality, which makes it superior for non-smooth decision boundaries like the Forest Cover dataset where tens of thousands of are needed.

Open in Lab
Watch how random grids partition 2D space. Points sharing a bin (same color) get similarity 1, others get 0. Averaging many grids approximates the kernel.
The demo wakes as you arrive…

Fourier vs Binning: when to use which

The two feature maps have complementary strengths:

Random Fourier Features produce smooth, continuous maps well-suited for interpolation tasks — problems where the decision boundary is smooth and the kernel is differentiable (e.g., Gaussian RBF). They excel on the CPU and Census regression benchmarks.

Random Binning Features produce piecewise-constant maps that explicitly preserve locality. They shine on memorization tasks — problems that need many support vectors and have rough, complex boundaries. The Forest Cover dataset is the dramatic example: binning achieves 2.2% error (matching exact SVM), while Fourier features struggle at 11.6%.

A practical rule of thumb: if the exact SVM needs few support vectors, Fourier features will work well. If it needs many, prefer binning. And since the two can be mixed freely, you can concatenate both types of features for the best of both worlds.

Convergence: how many features are enough?

A natural concern: how good is this approximation? The paper provides uniform convergence bounds — not just for a single pair (x,y)(x, y), but for all pairs simultaneously over a compact set MM.

For Random Fourier Features: with high probability, the worst-case approximation error across all pairs is bounded by ϵ\epsilon when the number of features is D=Ω ⁣(dϵ2log⁡σp⋅diam(M)ϵ)D = \Omega\!\left(\frac{d}{\epsilon^2} \log \frac{\sigma_p \cdot \text{diam}(M)}{\epsilon} \right), where σp2\sigma_p^2 is the second moment of the spectral distribution (the trace of the kernel's Hessian at the origin).

The key takeaway: DD depends on the data dimension dd and the desired accuracy ϵ\epsilon, not on the number of training points NN. Even for a million training examples, a few hundred random features can achieve sub-percent approximation error on standard kernels.

Pr⁡ ⁣[sup⁡x,y∈M∣z(x)⊤z(y)−k(x−y)∣≥ϵ]  ≤  28 ⁣(σp⋅diam(M)ϵ) ⁣2exp⁡ ⁣(−Dϵ24(d+2))\Pr\!\left[\sup_{x,y \in M} |z(x)^\top z(y) - k(x-y)| \geq \epsilon\right] \;\leq\; 2^8 \!\left(\frac{\sigma_p \cdot \text{diam}(M)}{\epsilon}\right)^{\!2} \exp\!\left(-\frac{D\epsilon^2}{4(d+2)}\right)
Uniform convergence bound for Random Fourier Features — The probability of the worst-case error exceeding ε decays exponentially with D. The bound is independent of N — a few hundred features suffice regardless of dataset size.
Open in Lab
Adjust D and ε to see how the convergence bound tightens. Notice the exponential decay with D.
The demo wakes as you arrive…

The algorithm in code

Random Fourier Features — complete implementationpython

Simplified to show the idea — not the real implementation.

import numpy as np

def random_fourier_features(X, kernel='rbf', gamma=1.0, D=300):
    """
    Map data X (N, d) to random Fourier features Z (N, D).
    Inner products Z @ Z.T ≈ kernel matrix K.

    kernel: 'rbf' (Gaussian) or 'laplacian'
    gamma:  kernel bandwidth parameter
    D:      number of random features
    """
    N, d = X.shape

    # Step 1: Draw random frequencies from kernel's spectral distribution
    if kernel == 'rbf':
        # Gaussian kernel → Gaussian spectral distribution
        W = np.random.randn(d, D) * np.sqrt(2 * gamma)
    elif kernel == 'laplacian':
        # Laplacian kernel → Cauchy spectral distribution
        W = np.random.standard_cauchy(size=(d, D)) * gamma

    # Step 2: Draw random phase shifts
    b = np.random.uniform(0, 2 * np.pi, size=D)

    # Step 3: Compute the feature map
    Z = np.sqrt(2 / D) * np.cos(X @ W + b)   # (N, D)

    return Z

# Usage: approximate Gaussian RBF kernel
X_train = np.random.randn(10000, 50)      # 10K points, 50 dims
Z = random_fourier_features(X_train, D=500)

# Now use any linear method on Z:
# w = ridge_regression(Z, y, lambda=0.01)
# prediction = Z_test @ w

Experimental results

The paper evaluates Random Features + ridge regression against Core Vector Machines (CVM) and exact SVMs on five large-scale benchmarks. The results are striking:

  • On CPU (6,500 instances, regression): Fourier features achieve 3.6% error in 20 seconds — exact SVM takes 31 seconds for 11% error.
  • On Adult (32K instances, classification): 14.9% error in 9 seconds vs. SVMlight's 15.1% in 7 minutes.
  • On Forest Cover (522K instances, classification): Binning features achieve 2.2% error in 25 minutes vs. libSVM's 2.2% in 44 hours.

Two additional findings stand out. First, accuracy keeps improving as the training set grows — doubling data reduces error by up to 40%, a luxury that exact kernel machines cannot afford. Second, good performance appears from a remarkably modest number of features: D=300D = 300 to 500500 for most datasets.

Open in Lab
Compare training time and error across methods. Random Features achieve similar accuracy orders of magnitude faster.
The demo wakes as you arrive…

The full pipeline

The complete Random Features workflow is refreshingly simple:

  1. Choose your kernel — Gaussian RBF, Laplacian, or any shift-invariant kernel.
  2. Compute the spectral distribution p(ω)p(\omega) — the Fourier transform of the kernel.
  3. Sample D random frequencies ω1,…,ωD\omega_1, \dots, \omega_D from p(ω)p(\omega) and D phases b1,…,bDb_1, \dots, b_D from Uniform[0,2π]\text{Uniform}[0, 2\pi].
  4. Transform every data point: z(x)=2/D [cos⁡(ω1⊤x+b1),…,cos⁡(ωD⊤x+bD)]⊤z(x) = \sqrt{2/D}\,[\cos(\omega_1^\top x + b_1), \dots, \cos(\omega_D^\top x + b_D)]^\top.
  5. Train a linear on the transformed data (ridge regression, linear SVM, etc.).
  6. Predict: f(x)=w⊤z(x)f(x) = w^\top z(x) — requires only O(D+d)O(D + d) operations.

The random frequencies are drawn once and reused for all data points. The entire pipeline replaces O(N2)O(N^2) kernel computation with O(ND)O(ND) feature computation plus O(ND2)O(ND^2) linear solving.

Open in Lab
Step through the Random Fourier Features pipeline. Click each stage to see the data transform in action.
The demo wakes as you arrive…

Why it changed the field

  1. 2007

    Random Features (this paper)

    Rahimi and Recht show that random cosine projections can approximate shift-invariant kernels, making kernel-quality learning accessible at scale.

  2. 2008

    Uniform approximation extension

    Rahimi and Recht extend the theory to uniform approximation of functions with random bases, strengthening the theoretical foundation.

  3. 2009

    Kitchen sinks

    "Weighted Sums of Random Kitchen Sinks" extends the idea to learn the optimal weighting of random features, further bridging random features and neural networks.

  4. 2017

    NeurIPS Test of Time Award

    The paper receives the Test of Time Award. In his acceptance speech, Rahimi calls for more rigorous empirical methodology in machine learning — the "alchemy" speech.

  5. 2018

    Neural Tangent Kernel

    Jacot et al. show that infinitely wide neural networks are equivalent to kernel machines — the NTK theory builds directly on the random features framework.

The bridge to neural networks

Look at the Random Fourier Feature map again: z(x)=2/D cos⁡(W⊤x+b)z(x) = \sqrt{2/D}\,\cos(W^\top x + b). This is exactly a one-hidden-layer with random, frozen weights WW and cosine activation — only the output layer is learned.

This observation is more than a coincidence. The Neural Tangent Kernel (NTK) theory (Jacot et al., 2018) shows that training an infinitely wide neural network with is equivalent to kernel regression with a specific kernel determined by the network architecture. Random Features are the finite-width, explicit-map version of this correspondence.

The Random Features paper planted the seed: kernel approximation via random projections is not just a computational trick — it reveals a deep structural connection between kernel methods and neural networks that reshaped how we think about both.

CitationRahimi, Recht. Random Features for Large-Scale Kernel Machines. NeurIPS, 2007.

Terms in this paper