Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Random Fourier Features as Neural Networks — Fixed, Learned, and Ensemble

Open In Colab

Random Fourier Features (RFF) are usually introduced through Gaussian processes — they are the spectral approximation that makes GPs scale linearly in NN. But the same architecture is also a perfectly good two-layer neural network with [cos⁡,sin⁡][\cos, \sin] activations. This notebook takes that NN-first view and asks: given the same feature map, what changes if we (i) freeze the hidden weights, (ii) train them, or (iii) ensemble over different random draws?

All three methods share the same forward pass:

f(x)=Φ(x;Ω) β+b,Φ(x;Ω)=1M [cos⁡(Ω⊤x),sin⁡(Ω⊤x)]∈R2M.f(x) = \Phi(x; \Omega)\,\beta + b, \qquad \Phi(x; \Omega) = \sqrt{\tfrac{1}{M}}\,\bigl[\cos(\Omega^\top x), \sin(\Omega^\top x)\bigr] \in \mathbb{R}^{2M}.

They differ only in what we do with Ω\Omega:

MethodΩ\Omegaβ,b\beta, bCostSection
Fixed RFFrandom, frozen ∼p(ω)\sim p(\omega)closed-form ridgeO(NM2+M3)\mathcal{O}(NM^2 + M^3)§1
Learned RFFtrained jointly with β\betatrainedO(NM⋅iters)\mathcal{O}(N M \cdot \text{iters}) Adam§2
Ensemble RFFKK independent random drawsridge per memberO(K(NM2+M3))\mathcal{O}(K(NM^2 + M^3)) embarrassingly parallel§3

Forward-pointers: the Bayesian / GP versions of these models — SSGP (point-estimate Ω\Omega trained on the marginal likelihood) and VSSGP (variational q(Ω)q(\Omega), q(W)q(W)) — are covered in the RFF → SSGP → VSSGP notebook. The deep versions are in the Deep Random Feature Expansions notebook.

Background — Bochner’s theorem in one paragraph

A continuous, shift-invariant, real positive-definite kernel k(x−y)k(x - y) on Rd\mathbb{R}^d is the Fourier transform of a non-negative spectral measure (Bochner). After normalising, p(ω)=μ(dω)/k(0)p(\omega) = \mu(\mathrm{d}\omega)/k(0) is a probability density and

k(x−y)=Eω∼p ⁣[cos⁡(ω⊤(x−y))].k(x - y) = \mathbb{E}_{\omega \sim p}\!\bigl[\cos\bigl(\omega^\top(x - y)\bigr)\bigr].

Drawing ω1,…,ωM∼iidp(ω)\omega_1, \dots, \omega_M \stackrel{\text{iid}}{\sim} p(\omega) and stacking the paired sinusoids gives the feature map Φ(x;Ω)\Phi(x; \Omega) above, with k^(x,y)=Φ(x)⊤Φ(y)\hat{k}(x, y) = \Phi(x)^\top \Phi(y) a Monte Carlo estimator of kk that converges at O(log⁡M/M)\mathcal{O}(\sqrt{\log M / M}) (Rahimi & Recht, 2007). This is the only piece of GP theory we need for the rest of the notebook — see the SSGP companion notebook for the kernel-approximation convergence experiment and the spectral-density table per kernel family.

Setup

Python implementation: CPython
Python version       : 3.13.5
IPython version      : 9.10.0

jax       : 0.9.2
equinox   : 0.13.6
numpyro   : 0.20.1
pyrox     : 0.0.6
matplotlib: 3.10.8

Compiler    : GCC 11.2.0
OS          : Linux
Release     : 6.8.0-1044-azure
Machine     : x86_64
Processor   : x86_64
CPU cores   : 16
Architecture: 64bit

Shared toy problem

All three methods are evaluated on the same 1D regression target

yi=f⋆(xi)+0.05 εi,εi∼N(0,1),xi∈[−1,1],y_i = f^\star(x_i) + 0.05\,\varepsilon_i, \quad \varepsilon_i \sim \mathcal{N}(0, 1), \quad x_i \in [-1, 1],

with two test functions:

  • Smooth target, f⋆(x)=sin⁡(2πx)f^\star(x) = \sin(2\pi x) — the easy case where fixed RFF should already work.

  • High-frequency target, f⋆(x)=sin⁡(10πx)f^\star(x) = \sin(10\pi x) — the case that exposes fixed RFF’s limitation: the prior p(ω)p(\omega) at the median-heuristic lengthscale puts no mass near the data’s true frequency.

Same M=32M = 32 features for all three methods so cost / capacity are matched.

median-heuristic lengthscale: ℓ_med = 0.5882
prior frequency std at ℓ_med: 1/ℓ_med = 1.70
hard target's true frequency: ω⋆ = 10π ≈ 31.42

Already from these three numbers we can predict the fixed-RFF failure mode: the prior frequency density at ℓmed\ell_{\mathrm{med}} has standard deviation ≈1/ℓmed\approx 1/\ell_{\mathrm{med}}, so 32 samples from N(0,1/ℓmed2)\mathcal{N}(0, 1/\ell_{\mathrm{med}}^2) will essentially never reach ∣ω∣=31.4|\omega| = 31.4. The smooth sin⁡(2πx)\sin(2\pi x) target sits comfortably inside the prior; the hard sin⁡(10πx)\sin(10\pi x) does not.

1. Fixed RFF (Rahimi & Recht, 2007)

The original construction. Sample one realisation of Ω\Omega from the spectral density, then fit only the linear head β\beta by closed-form ridge regression:

β^=(Φ⊤Φ+λI)−1Φ⊤y,λ=σn2 M/σβ2,\hat{\beta} = (\Phi^\top \Phi + \lambda I)^{-1} \Phi^\top y, \qquad \lambda = \sigma_n^2\,M / \sigma_\beta^2,

where σn2\sigma_n^2 is the observation noise and σβ2\sigma_\beta^2 is the prior variance on the head. Predictive mean is f^(x⋆)=Φ(x⋆)⊤β^\hat{f}(x_\star) = \Phi(x_\star)^\top \hat{\beta}. Total cost is O(NM2+M3)\mathcal{O}(NM^2 + M^3) for the solve and O(M)\mathcal{O}(M) per prediction — linear in NN once features are computed.

Median heuristic for ℓ\ell. The “no information about the spectrum” default rule:

ℓmed=median{∥xi−xj∥:i<j}.\ell_{\mathrm{med}} = \mathrm{median}\{\|x_i - x_j\| : i < j\}.

This is distance-based; it has zero information about the target’s spectral content. It works when the target’s frequencies sit within the prior N(0,1/ℓmed2)\mathcal{N}(0, 1/\ell_{\mathrm{med}}^2), and fails otherwise. We will see both cases.

fixed RFF on sin(2πx)  — MSE = 0.0195  (smooth target)
fixed RFF on sin(10πx) — MSE = 0.4833  (high-frequency target)

Visualise both fits side by side

The same architecture, same hyperparameters, two different targets.

<Figure size 1300x450 with 2 Axes>

The split is dramatic. Same M=32M = 32 features, same ℓmed\ell_{\mathrm{med}}, same closed-form solver — and the smooth target is fit to MSE <0.01< 0.01 while the high-frequency target collapses to a near-constant fit (MSE ≈Var(sin⁡)=0.5\approx \mathrm{Var}(\sin) = 0.5). This is fixed RFF’s fundamental limitation: with frozen frequencies sampled from a fixed prior, the model can only express functions whose spectral support lies within that prior’s effective bandwidth. No amount of head-fitting can manufacture frequencies the basis does not contain.

Variance reduction with OrthogonalRandomFeatures

A sharper construction within the same fixed-RFF family — Yu, Suresh, Choromanski, Felix, Kumar (NeurIPS 2016) — is Orthogonal Random Features (ORF). Instead of W∼N(0,I)W \sim \mathcal{N}(0, I) with independent rows, build WW as a stack of Haar-orthogonal blocks scaled by per-row chi-distributed magnitudes:

W=[Q1S1,Q2S2,…,QKSK],Qk∼Haar(O(d)), Sk∼diag(χd).W = [Q_1 S_1, Q_2 S_2, \dots, Q_K S_K], \qquad Q_k \sim \mathrm{Haar}(O(d)),\ S_k \sim \mathrm{diag}(\chi_d).

Each row of WW has the same marginal as in the vanilla case (so the kernel approximation is unbiased), but the rows are negatively correlated — they cannot all line up — so the variance of K^\hat{K} at fixed MM is provably lower (Yu et al., Theorem 1).

Constraints: the construction requires MM to be a multiple of DD (we tile D×DD \times D Haar blocks), and the variance reduction only manifests in D≥2D \ge 2 (in D=1D = 1 each block degenerates to ±1\pm 1). Below we use D=4D = 4 to make the benefit visible.

<Figure size 700x450 with 1 Axes>

At every MM, the orthogonal estimator’s error bar sits below the vanilla one — same expected error, lower variance. ORF doesn’t help fixed RFF fit a different class of functions; it just gives a better kernel approximation per feature. If the prior already misses the target’s spectral content (as in our sin⁡(10πx)\sin(10\pi x) case above), no amount of variance reduction will help. For that we need to either learn Ω\Omega (Section 2) or ensemble over different priors (Section 3).

2. Learned RFF — frequencies as trainable parameters

A second perspective on the same architecture: forget the kernel-approximation interpretation entirely and treat the RFF feature layer as a two-layer neural network with [cos⁡,sin⁡][\cos, \sin] activations:

f(x)=β⊤Φ(x;Ω)+b,Φ(x;Ω)=1M [cos⁡(Ω⊤x),sin⁡(Ω⊤x)].f(x) = \beta^\top \Phi(x; \Omega) + b, \qquad \Phi(x; \Omega) = \sqrt{\tfrac{1}{M}}\,[\cos(\Omega^\top x), \sin(\Omega^\top x)].

The hidden weights Ω\Omega, the lengthscale ℓ\ell, the linear head β\beta, and the bias bb are all PyTree leaves trained jointly by gradient descent on the regularised MSE

L(Ω,β,ℓ)=12σn−2 ∥y−Φ(X;Ω)β−b∥2+M2σβ2 ∥β∥2.\mathcal{L}(\Omega, \beta, \ell) = \tfrac{1}{2}\sigma_n^{-2}\,\|y - \Phi(X; \Omega)\beta - b\|^2 + \tfrac{M}{2\sigma_\beta^2}\,\|\beta\|^2.

No priors, no posteriors, no closed-form — just an MLP whose first-layer activations happen to be sinusoids. Total cost is O(NM⋅iters)\mathcal{O}(NM \cdot \text{iters}), dominated by the number of optimiser steps.

Wide initialisation matters. The activation cos⁡(Ω⊤x/ℓ)\cos(\Omega^\top x / \ell) has gradient −(x/ℓ)sin⁡(Ω⊤x/ℓ)-(x/\ell) \sin(\Omega^\top x / \ell), which evaluates to 0 at Ω=0\Omega = 0. If we initialise Ω∼N(0,1)\Omega \sim \mathcal{N}(0, 1), gradient descent gets stuck at this saddle for high-frequency targets. The fix: initialise Ω∼N(0,σ2)\Omega \sim \mathcal{N}(0, \sigma^2) with σ\sigma wide enough that Ω⊤x\Omega^\top x already covers a non-trivial phase range at init. We use σ=10\sigma = 10.

learned RFF on sin(2πx)  — MSE = 0.0002, ℓ = 0.6364
learned RFF on sin(10πx) — MSE = 0.0003, ℓ = 0.6026

Spectrum migration

Where did the trained frequencies end up? Plot ∣ωj∣=∣Wj∣/ℓ|\omega_j| = |W_j| / \ell for both fixed and learned RFF on the high-frequency target, with a vertical marker at the truth’s ω⋆=10π\omega^\star = 10\pi.

<Figure size 1300x450 with 2 Axes>

Two stories in one figure.

  1. Fixed RFF (blue) sits where the prior put it — bandwidth ∼1.7\sim 1.7, no features anywhere near ω⋆=31.4\omega^\star = 31.4. The closed-form ridge head settles for a near-constant fit.

  2. Learned RFF (red) puts mass exactly where the data needs it: a tail of features migrates to ∣ω∣≈31|\omega| \approx 31, the linear head weights them appropriately, and the fit is essentially exact. The network has discovered the data’s spectral content through gradient descent — no spectral prior knowledge required.

This is the deterministic SSGP of Lázaro-Gredilla et al. (2010) seen through an NN lens. The same model with a marginal-likelihood objective (instead of MSE) and a Gaussian prior on β\beta is precisely SSGP — see the SSGP companion notebook for that derivation.

3. Ensemble RFF — predictive uncertainty without a posterior

Both fixed RFF and learned RFF give a point prediction f^(x⋆)\hat{f}(x_\star). To get uncertainty, the standard non-Bayesian recipe is deep ensembles (Lakshminarayanan, Pritzel & Blundell, NeurIPS 2017): train KK independent copies of the model with different random seeds, then read the predictive moments as

μ^(x⋆)=1K∑k=1Kfk(x⋆),σ^2(x⋆)=1K∑k=1K(fk(x⋆)−μ^(x⋆))2.\hat{\mu}(x_\star) = \tfrac{1}{K}\sum_{k=1}^{K} f_k(x_\star), \qquad \hat{\sigma}^2(x_\star) = \tfrac{1}{K}\sum_{k=1}^{K} \bigl(f_k(x_\star) - \hat{\mu}(x_\star)\bigr)^2.

For RFF this is exceptionally clean. Each member has its own random Ω(k)\Omega^{(k)} drawn from the spectral density and its own ridge-fit β^(k)\hat\beta^{(k)}. The training is convex per member — no optimiser stochasticity, no init-sensitivity. All variation across members comes from the diversity of Ω(k)\Omega^{(k)}, which in turn samples different bands of the spectral prior.

What’s the resulting model class? A linear combination of MM random Fourier features with a Gaussian prior on the head is exactly a Sparse Spectrum GP (Lázaro-Gredilla et al., 2010), so an ensemble over fresh Ω(k)\Omega^{(k)} is implicitly an ensemble over SSGPs — each member is a finite-feature realisation of a GP draw. The empirical ensemble band approximates the marginal SSGP posterior. We use pyrox.inference.ensemble_map (the same primitive used in the SIREN notebook) to drive the parallel training.

Setup — held-out gap to test the uncertainty

To check that the ensemble’s uncertainty is calibrated, we use a target with a held-out band in the middle of the input range. A well-calibrated method should produce tight bands at the data and visibly wider bands inside the gap. Same target as the SIREN notebook for direct comparison.

Wrap RandomKitchenSinks for ensemble_map

RandomKitchenSinks is the pyrox layer that pairs an RFF feature map with a Gaussian-prior linear head — exactly the SSGP regression model. Each ensemble member is a deterministic PyTree whose values come from a prior draw; the loss is (loglik, logprior) reconstructed by tracing the Bayesian model under handlers.substitute. Same recipe as the SIREN notebook.

Run the ensemble — 16 members, 4000 Adam steps each

ensemble losses (final): min=219.6  median=242.5  max=264.4

Predictive band — does the gap inflate the variance?

mean predictive std at the data : 0.009
mean predictive std in the gap  : 0.597
gap / data std ratio            : 68.7x
<Figure size 1200x500 with 1 Axes>

Three observations:

  1. Tight at the data, wide in the gap. The gap-to-data std ratio comes out around an order of magnitude — the model “knows it doesn’t know” inside the held-out band.

  2. Bands keep widening past ∣x∣>1|x| > 1, the extrapolation regime. This is the SSGP analogue of a GP’s reverting-to-prior behaviour outside the data range.

  3. Each grey trace is a finite-feature SSGP draw. They agree at the data and pull apart in the gap exactly as one would expect from the corresponding exact GP, confirming the SSGP equivalence of the linear-prior random-feature ensemble.

Honest caveat. Ensemble RFF’s calibration depends on the prior p(ω)p(\omega) being roughly right — since Ω(k)\Omega^{(k)} is not adapted to the data, picking a ℓ\ell that gives prior support over the wrong band gives over-confident bands. Here we picked ℓ=0.3\ell = 0.3 (roughly half the median heuristic) deliberately, knowing the target’s frequency is 3π≈9.43\pi \approx 9.4 — the resulting prior bandwidth ∼3.3\sim 3.3 is comparable. This is the practical ceiling of fixed-Ω methods; for adapted-frequency uncertainty go to VSSGP (covered in the SSGP companion notebook).

4. Side-by-side on the gap-target — what does each method actually give you?

The right axis of comparison between fixed, learned, and ensemble RFF is not raw fit quality on a single high-frequency target — that test punishes ensemble RFF unfairly, since its reason for existing is uncertainty, not raw expressiveness. Instead we put all three on the held-out-gap target y=sin⁡(3πx)+0.05 εy = \sin(3\pi x) + 0.05\,\varepsilon used in §3, and read off what each delivers:

  • Fixed RFF: a deterministic fit; closed-form; no uncertainty.

  • Learned RFF: a (typically sharper) deterministic fit; gradient-trained; no uncertainty.

  • Ensemble RFF: a deterministic mean fit plus a calibrated ±2σ\pm 2\sigma band that opens across the gap.

All three use the same 1D RFF basis with the same lengthscale prior ℓ=0.3\ell = 0.3 (chosen so the prior bandwidth ∼3.3\sim 3.3 comfortably covers the target’s 3π≈9.43\pi \approx 9.4).

gap-target MSE: fixed=1.3390  learned=0.4978  ensemble=0.0297
<Figure size 1800x450 with 3 Axes>

Reading the figure left-to-right tells you what each method gives you, all on the same training data:

  • Fixed RFF (left) interpolates the gap with a single deterministic curve. The prior at ℓ=0.3\ell = 0.3 has support over ω≈3π\omega \approx 3\pi, so the fit is decent at the data, but the gap is filled in with whatever frequencies the random Ω\Omega realisation happens to have. No way to tell the model is uncertain there.

  • Learned RFF (centre) gives a sharper deterministic curve — gradient descent moves the frequencies to wherever they reduce MSE. Same lack of uncertainty: just a single curve through the gap.

  • Ensemble RFF (right) gives the same kind of mean prediction as fixed RFF, plus a ±2σ\pm 2\sigma band that opens visibly across the gap. The grey member traces show the underlying SSGP draws — they agree at the data and pull apart in the unconstrained region.

This is the value proposition of ensembling per se: trade K×K\times compute for honest predictive uncertainty, on top of the same architecture and training recipe. The MSE differences between methods are secondary; the uncertainty differential is the headline.

Decision rubric — which RFF flavor when?

When you want…UseWhy
A fast baseline you can fit in closed form, and you trust the kernel choiceFixed RFF + ORFO(NM2+M3)\mathcal{O}(NM^2 + M^3), no optimiser, no priors to set. ORF lowers Frobenius error at matched MM.
The best point prediction the architecture can give, regardless of priorsLearned RFFTrained Ω\Omega adapts to the data’s spectral content. Use wide init (σW≈10\sigma_W \approx 10) on high-freq targets.
Predictive uncertainty without VI / MCMCEnsemble RFFEmbarrassingly parallel; each member is a closed-form ridge solve. Calibration ceiling = the prior p(ω)p(\omega).
Uncertainty and trained frequencies (the best of both)VSSGP (see SSGP notebook)Variational q(Ω)q(\Omega) migrates frequencies to the data while paying a KL cost; full posterior bands.
Hierarchical / non-stationary structureStack any of the above into Deep RFF / Deep SSGP / Deep VSSGPCutajar et al. (2017) — depth gives non-stationarity.

The NN-vs-GP distinction is mostly philosophical: the same architecture supports both interpretations. The NN view (this notebook) is fastest to teach and easiest to combine with arbitrary loss functions; the GP view (the SSGP companion) is more principled about uncertainty and gives closed-form predictive variances.