Neural Networks Approximation
What multilayer perceptrons can approximate: Cybenko, Hornik, Leshno–Pinkus, Barron, depth separation, minimal width, and extensions to operators, CNNs and Transformers.
Learning goals: state the approximation theorems precisely, follow their proofs, tell the differences between density, rate and separation results, and know what they do not say about training and generalization. Each result comes with an interactive illustration on a machine-learning example, and with the Python code that reproduces it.
Context and map of the results
What an approximation theorem says
A multilayer perceptron (MLP) of depth $L$ is a composition $F=A_{L+1}\circ\phi\circ A_L\circ\cdots\circ\phi\circ A_1$ of affine maps $A_l(x)=W_lx+b_l$ and a fixed scalar activation $\phi$ applied coordinatewise. With one hidden layer, $F(x)=c+\sum_{i=1}^{N}\alpha_i\,\phi(\omega_i^{\top}x+b_i)$. The universal approximation theorems answer the question: is the class of functions computed by such networks rich enough? The answer depends on four choices that the headline "neural networks are universal approximators" hides:
- the function space and the norm: continuous functions on a compact set for the uniform norm, $L^p$ functions, operators…;
- the activation: sigmoid, bounded, ReLU, any non-polynomial function…;
- the architecture: one hidden layer of any width, or any depth with a bounded width, or a convolutional or attention-based network;
- the quantifiers: density (an approximation exists, with no bound on its size), a rate (how fast the error decreases with the number of neurons), a separation (some architectures need exponentially more neurons than others).
This page gathers the main results, with their statements, proofs (full when short, otherwise an outline that says what is skipped), and above all their differences and limits. The proof of Cybenko’s theorem, formerly in Neural networks with Keras, is Part 1. Two small exercises let you check the key mechanisms with Keras.
Map of the results
| Result | Architecture | Activation | Claim | Not claimed |
|---|---|---|---|---|
| Cybenko 1989, Hornik et al. 1989 | 1 hidden layer | sigmoidal (bounded, monotone) | dense in $\mathcal C(K)$, uniform norm | size of the network; training |
| Hornik 1991, Leshno et al. 1993 | 1 hidden layer | continuous, not a polynomial (ReLU included) | dense in $\mathcal C(K)$; the condition is necessary and sufficient | size; training |
| Barron 1993 | 1 hidden layer, $N$ units | sigmoidal | error $\le 2rC_f/\sqrt N$ in $L^2$ if $C_f<\infty$ | $C_f$ may be huge; training |
| Telgarsky 2016, Eldan–Shamir 2016 | depth against width | ReLU (and others) | some functions are exponentially cheaper with depth | that typical targets are such functions |
| Lu et al. 2017, Hanin–Sellke 2017, Kidger–Lyons 2020, Park et al. 2021 | bounded width, any depth | ReLU, or general | minimal width $\approx n+1$ (input dimension $n$) | depth needed |
| Chen–Chen 1995, Zhou 2020, Yun et al. 2020 | operators, CNN, Transformers | non-polynomial | density in the corresponding space | size; training; generalization |
Reading rule: a density theorem is an existence statement. It never tells you how many neurons to take, how to find the weights, or how the network behaves on data that were not used to choose them.
Part 1 · One hidden layer: density (Cybenko, Hornik, Leshno–Pinkus)
Cybenko and Hornik: density for sigmoidal activations
For an activation $\phi:\mathbb R\to\mathbb R$, let $\mathcal N_\phi(m)$ be the set of functions $F(x)=\sum_{i=1}^N\alpha_i\,\phi(\omega_i^{\top}x+b_i)$ on $\mathbb R^m$, with $N\in\mathbb N$ arbitrary and $\alpha_i,b_i\in\mathbb R$, $\omega_i\in\mathbb R^m$. We say that $\mathcal N_\phi(m)$ is dense in $\mathcal C(K)$ if for every continuous $f$ on a compact set $K\subset\mathbb R^m$ and every $\varepsilon>0$ there is $F\in\mathcal N_\phi(m)$ with $\sup_{K}|F-f|<\varepsilon$. A function is sigmoidal if it has limits $0$ at $-\infty$ and $1$ at $+\infty$.
Let $\phi$ be continuous, bounded, non-constant and non-decreasing (for instance a sigmoid or $\tanh$). Then $\mathcal N_\phi(m)$ is dense in $\mathcal C(I_m)$, $I_m=[0,1]^m$, for the uniform norm. Since any compact set is contained in a cube, it is dense in $\mathcal C(K)$ for every compact $K\subset\mathbb R^m$.
Proof
Let $S$ be the vector space of functions $x\mapsto\sum_i\alpha_i\phi(\omega_i^Tx+b_i)$ and $\bar S$ its closure for the uniform norm on $I_m$; $\bar S$ is a vector space. Taking $\omega=0$ shows that $S$ contains the constants $\phi(b)$, hence all constants because $\phi\not\equiv0$.
Step 1: dimension one. Being monotone, bounded and non-constant, $\phi$ has limits $a<c$ at $-\infty$ and $+\infty$. Put $\psi=(\phi-a)/(c-a)$: it is non-decreasing with limits $0$ and $1$, hence $0\le\psi\le1$. Let $g$ be continuous on $[-R,R]$ and $\varepsilon>0$. By uniform continuity, choose $\delta$ with $|g(s)-g(t)|<\varepsilon/2$ whenever $|s-t|<\delta$, a subdivision $-R=t_0<\dots<t_n=R$ of mesh smaller than $\delta/2$, and $\eta<\delta/2$ smaller than half the mesh. Set $d_j=g(t_j)-g(t_{j-1})$ and
$$G_\lambda(t)=g(t_0)+\sum_{j=1}^n d_j\,\psi\big(\lambda(t-t_j)\big).$$$G_\lambda$ is a sum of constants and terms $\phi(\lambda t+b)$, so it lies in $S$ (one variable). Choose $\lambda$ so large that $\psi(\lambda u)$ is within $\gamma$ of $0$ for $u\le-\eta$ and of $1$ for $u\ge\eta$, where $\gamma\sum_j|d_j|<\varepsilon/4$. If $t\in[t_{k-1}+\eta,\,t_k-\eta]$, all steps $j\le k-1$ are on, all steps $j\ge k$ are off, so $|G_\lambda(t)-g(t_{k-1})|<\varepsilon/4$, and $|g(t)-g(t_{k-1})|<\varepsilon/2$: the error is below $3\varepsilon/4$. If $|t-t_k|<\eta$, only the $k$-th step is undecided with value $\theta\in[0,1]$, so $G_\lambda(t)$ is within $\varepsilon/4$ of $g(t_{k-1})+\theta d_k$, a number between $g(t_{k-1})$ and $g(t_k)$, both within $\varepsilon/2$ of $g(t)$. Hence $\|G_\lambda-g\|_\infty<\varepsilon$.
Step 2: cosines. Fix $\omega\in\mathbb R^m$ and $b\in\mathbb R$. For $x\in I_m$, $t=\omega^Tx$ lies in $[-R,R]$ with $R=\|\omega\|\sqrt m$. Step 1 applied to $g(t)=\cos(t+b)$ gives $\sum_i\alpha_i\phi(\lambda_it+b_i)$ uniformly close to it; replacing $t$ by $\omega^Tx$ gives an element of $S$ uniformly close to $x\mapsto\cos(\omega^Tx+b)$ on $I_m$. So these functions belong to $\bar S$, and so does the vector space $A$ they span.
Step 3: Stone–Weierstrass. $A$ is an algebra, since $\cos u\cos v=\tfrac12[\cos(u-v)+\cos(u+v)]$. It contains the constants ($\omega=0$, $b=0$). It separates points: if $x\ne y$ in $I_m$, take $\omega=s(x-y)$ with $s>0$ so small that $|\omega^Tx|,|\omega^Ty|<\pi/2$, and $b=-\pi/2$, so that $\cos(\omega^Tx+b)=\sin(\omega^Tx)\ne\sin(\omega^Ty)$ because $\sin$ is strictly increasing on $(-\pi/2,\pi/2)$ and $\omega^T(x-y)=s\|x-y\|^2>0$. By the Stone–Weierstrass theorem, $A$ is dense in $\mathcal C(I_m)$. Since $A\subset\bar S$ and $\bar S$ is closed, $\bar S=\mathcal C(I_m)$. $\square$
Interactive illustration. Fit a sensor curve with $N$ hidden sigmoidal units.
# Cybenko's theorem, step 1: a sum of N sharpened sigmoids that follows a curve g.import numpy as npimport matplotlib.pyplot as pltdef psi(z): # a sigmoidal function: limits 0 and 1 return 1 / (1 + np.exp(-np.clip(z, -60, 60)))g = lambda t: np.sin(2 * np.pi * t) + 0.5 * t # the curve to approximate (try the unit step!)t = np.linspace(0, 1, 2001)def network(N, lam): knots = np.linspace(0, 1, N + 1) d = np.diff(g(knots)) # increments d_j = g(t_j) - g(t_{j-1}) return g(0) + sum(d[j - 1] * psi(lam * (t - knots[j])) for j in range(1, N + 1))Ns = [2 ** e for e in range(0, 9)]lams = [10 ** a for a in (0, 1, 2, 3, 4, 5)]err = np.array([[np.max(np.abs(network(N, lam) - g(t))) for N in Ns] for lam in lams])print("sup error, rows: lambda = 1e0 ... 1e5, columns: N = 1, 2, 4, ..., 256")print(np.round(err, 3))fig, ax = plt.subplots(1, 2, figsize=(11, 4))ax[0].plot(t, g(t), "k", label="g")ax[0].plot(t, network(24, 1000), "C1", label="N = 24, lambda = 1000")ax[0].legend(); ax[0].set_title("a sum of 24 sigmoids")im = ax[1].imshow(np.log10(err), origin="lower", aspect="auto", extent=[-0.5, 8.5, -0.5, 5.5])ax[1].set_xlabel("log2 N"); ax[1].set_ylabel("log10 lambda"); ax[1].set_title("log10 of the sup error")plt.colorbar(im, ax=ax[1]); plt.show()
Differences with the original papers. Cybenko assumes only that $\phi$ is continuous and sigmoidal (no monotonicity) and proves it by duality (next proposition). Hornik, Stinchcombe and White prove density for non-decreasing bounded $\phi$ (also in $L^p(\mu)$ and for derivatives) with arguments close to the one above. The proof above is the constructive one: Step 1 shows how the weights are built (a staircase of sharpened sigmoids), but with a number of terms that grows like the inverse of the modulus of continuity, with no control on the dimension.
Cybenko's proof by duality
Let $\phi$ be continuous and sigmoidal. If a finite signed Borel measure $\mu$ on $I_m$ satisfies $\int_{I_m}\phi(\omega^{\top}x+b)\,d\mu(x)=0$ for all $\omega\in\mathbb R^m$, $b\in\mathbb R$, then $\mu=0$ ($\phi$ is discriminatory). Consequently $\mathcal N_\phi(m)$ is dense in $\mathcal C(I_m)$.
Proof
Discriminatory implies dense. If the closure $\bar S$ of $\mathcal N_\phi(m)$ were a proper closed subspace of $\mathcal C(I_m)$, the Hahn–Banach theorem would give a non-zero continuous linear functional vanishing on $\bar S$; by the Riesz representation theorem it is $h\mapsto\int h\,d\mu$ for a finite signed measure $\mu\ne0$, with $\int\phi(\omega^{\top}x+b)\,d\mu=0$ for all $\omega,b$: this contradicts the discriminatory property.
Continuous sigmoidal implies discriminatory. For $\omega\ne0$, $\lambda>0$ and $\theta,b\in\mathbb R$ put $\gamma_\lambda(x)=\phi(\lambda(\omega^{\top}x+b)+\theta)$. As $\lambda\to+\infty$, $\gamma_\lambda(x)\to1$ if $\omega^{\top}x+b>0$, $\to0$ if $\omega^{\top}x+b<0$ and $=\phi(\theta)$ on the hyperplane $\omega^{\top}x+b=0$; the family is bounded by $\sup|\phi|$. By dominated convergence, $0=\int\gamma_\lambda\,d\mu\to\mu(\{\omega^{\top}x+b>0\})+\phi(\theta)\mu(\{\omega^{\top}x+b=0\})$. Letting $\theta\to-\infty$ gives $\mu(\{\omega^{\top}x+b>0\})=0$ and then $\mu(\{\omega^{\top}x+b=0\})=0$, for every open half-space. Fix $\omega$: the pushforward $\nu=(\omega^{\top})_{\#}\mu$ on $\mathbb R$ gives zero mass to every half-line $[t,\infty)$, hence to every interval, hence $\nu=0$, hence $\int e^{is\,\omega^{\top}x}\,d\mu(x)=\int e^{is\,t}\,d\nu(t)=0$ for all $s$ and $\omega$: the Fourier transform of $\mu$ vanishes and $\mu=0$. $\square$
Interactive illustration. Learn the probability map of a two-class problem with logistic neurons, one at a time.
# Why density holds: a nonzero residual always correlates with some ridge function (greedy pursuit on a 2D map).import numpy as npimport matplotlib.pyplot as pltrng = np.random.default_rng(1)n = 32x, y = np.meshgrid((np.arange(n) + 0.5) / n, 1 - (np.arange(n) + 0.5) / n)P = np.stack([x.ravel(), y.ravel()], axis=1) # the 1024 pixels of [0, 1]^2sig = lambda z: 1 / (1 + np.exp(-np.clip(z, -60, 60)))def arc_distance(c, r, a0, a1): # distance of each pixel to a half circle a = np.linspace(a0, a1, 60) pts = np.stack([c[0] + r * np.cos(a), c[1] + r * np.sin(a)], axis=1) return np.min(np.linalg.norm(P[:, None] - pts[None], axis=2), axis=1)f = sig(25 * (arc_distance((0.62, 0.45), 0.25, np.pi, 2 * np.pi) - arc_distance((0.38, 0.55), 0.25, 0, np.pi))) # P(class 1 | pixel), two moonsA = 600 # dictionary of ridge functions sigma(s w.(x - p))ang, scale, p0 = rng.uniform(0, 2 * np.pi, A), 12 * rng.uniform(0.5, 1.5, A), rng.uniform(0.15, 0.85, (A, 2))atoms = np.array([sig(s * ((P - p) @ [np.cos(a), np.sin(a)])) for a, s, p in zip(ang, scale, p0)])norms = np.linalg.norm(atoms, axis=1)chosen, residual, history = [], f.copy(), []for k in range(40): corr = np.abs(atoms @ residual) / (norms * np.linalg.norm(residual)) # normalized correlation with the residual corr[chosen] = 0 chosen.append(int(np.argmax(corr))) # the ridge function that correlates most coef, *_ = np.linalg.lstsq(atoms[chosen].T, f, rcond=None) # refit all the output weights residual = f - atoms[chosen].T @ coef history.append((np.linalg.norm(residual) / np.linalg.norm(f), corr.max())) if k % 8 == 7: print(f"k = {k + 1:2d} units: relative residual {history[-1][0]:.3f}, best correlation {history[-1][1]:.3f}")fig, ax = plt.subplots(1, 4, figsize=(14, 3.4))for a, im, title in zip(ax, (f, f - residual, residual), ("target f", f"network, k = {len(chosen)}", "residual")): a.imshow(im.reshape(n, n), cmap="RdBu_r" if title == "residual" else "Blues"); a.set_title(title); a.axis("off")ax[3].semilogy([h[0] for h in history], label="relative residual"); ax[3].semilogy([h[1] for h in history], label="best correlation")ax[3].set_xlabel("k"); ax[3].legend(); plt.show()
This is the proof of the original paper. It is non-constructive (Hahn–Banach) but needs no monotonicity: it works for any continuous sigmoidal $\phi$, and extends to the measures of Hornik. It does not say how many neurons are needed.
Hornik 1991, Leshno–Lin–Pinkus–Schocken 1993: the exact condition
Let $\phi:\mathbb R\to\mathbb R$ be continuous. Then $\mathcal N_\phi(m)$ is dense in $\mathcal C(K)$ for every compact $K\subset\mathbb R^m$ if and only if $\phi$ is not a polynomial. (The original statement of Leshno et al. holds for locally bounded $\phi$ whose set of discontinuities has measure zero, with “not a polynomial” understood almost everywhere.)
Proof
Necessity. If $\phi$ is a polynomial of degree $k$, every function $\phi(\omega^{\top}x+b)$ is a polynomial of degree $\le k$ in $x$. The space of such polynomials has finite dimension, so it is closed in $\mathcal C(K)$ and cannot be dense (it does not contain $x\mapsto x_1^{k+1}$ at distance below some positive number).
Sufficiency, smooth case. Assume $\phi\in\mathcal C^\infty$ and that no derivative is identically zero at a well chosen point: there exists $b_0$ with $\phi^{(k)}(b_0)\ne0$ for all $k\ge0$. (This is the classical lemma of Corominas and Sunyer: a $\mathcal C^\infty$ function such that at every point some derivative vanishes is a polynomial. The proof is a Baire argument on the closed sets $\{\phi^{(k)}=0\}$ and is omitted.) Let $\bar S$ be the closure of $\mathcal N_\phi(m)$ in $\mathcal C(K)$. For $\omega\in\mathbb R^m$ the functions $\lambda\mapsto\phi(\lambda\,\omega^{\top}x+b_0)$ lie in $\mathcal N_\phi(m)$, and so do their finite differences in $\lambda$. Since $\partial_\lambda^k\phi(\lambda\,\omega^{\top}x+b_0)\big|_{\lambda=0}=(\omega^{\top}x)^k\phi^{(k)}(b_0)$ and finite differences of order $k$ converge to this derivative uniformly on $K$, we get $(\omega^{\top}x)^k\in\bar S$ for every $k$ and $\omega$. The powers $(\omega^{\top}x)^k$ span all homogeneous polynomials of degree $k$ (polarization), so all polynomials belong to $\bar S$, which is therefore $\mathcal C(K)$ by the Weierstrass theorem.
Sufficiency, general continuous case. For $\rho\in\mathcal C_c^\infty(\mathbb R)$ the convolution $\phi_\rho=\phi*\rho$ is $\mathcal C^\infty$ and lies in the closure of $\mathrm{span}\{\phi(t+b)\}$ for the uniform norm on compact sets (Riemann sums of $\int\phi(t-s)\rho(s)\,ds$). Hence $\mathcal N_{\phi_\rho}(m)\subset\bar S$. If $\phi_\rho$ were a polynomial for every $\rho$, the sets $\{\rho:\deg\phi_\rho\le k\}$ would be closed and cover the complete metric space $\mathcal C_c^\infty$ (on a fixed support); by Baire one of them has non-empty interior, hence by linearity is everything, so $\phi*\rho_\varepsilon$ would be a polynomial of degree $\le k$ for a mollifier $\rho_\varepsilon\to\delta$, and the limit $\phi=\lim\phi*\rho_\varepsilon$ (uniform on compacts, in the closed space of polynomials of degree $\le k$) would be a polynomial. So some $\phi_\rho$ is a smooth non-polynomial, and the smooth case gives $\bar S=\mathcal C(K)$. $\square$
Interactive illustration. Regression with $N$ random hidden units, for eight activation functions.
# Leshno-Pinkus: with random hidden units, only the activations that are not polynomials keep improving.import numpy as npimport matplotlib.pyplot as pltacts = {"tanh": np.tanh, "relu": lambda z: np.maximum(z, 0), "gauss": lambda z: np.exp(-z ** 2), "sin": np.sin, "relu^2": lambda z: np.maximum(z, 0) ** 2, "z^2": lambda z: z ** 2, "z^3": lambda z: z ** 3, "z^5": lambda z: z ** 5}x = np.linspace(-1, 1, 121)target = 0.6 * np.sin(3 * x) + 0.3 * np.cos(7 * x)rng = np.random.default_rng(5)omega = 3 * rng.normal(size=30)b = -omega * rng.uniform(-1, 1, 30) # the kink / centre of every unit lies inside [-1, 1]# the same 30 random units are used for every activationdef sup_error(phi, N): H = phi(np.outer(x, omega[:N]) + b[:N]) # hidden layer: 121 x N alpha, *_ = np.linalg.lstsq(H, target, rcond=None) # output weights by least squares return np.max(np.abs(H @ alpha - target))for name, phi in acts.items(): print(f"{name:7s} N = 5, 10, 20, 30 ->", np.array([sup_error(phi, N) for N in (5, 10, 20, 30)]).round(5))for name, phi in acts.items(): plt.semilogy(range(1, 31), [max(sup_error(phi, N), 1e-9) for N in range(1, 31)], "--" if name.startswith("z^") else "-", label=name)plt.xlabel("number of hidden units N"); plt.ylabel("sup error"); plt.legend(); plt.title("polynomial activations (dashed) stall"); plt.show()
Consequences. (i) Hornik (1991) proves density for $\phi$ continuous, bounded and non-constant: such a $\phi$ is not a polynomial, so it is a special case. (ii) $\tanh$, softplus, GELU, sine, ReLU are covered; a polynomial activation or $x\mapsto x$ is not: a network with polynomial activations of degree $d$ and $L$ layers only produces polynomials of degree $\le d^L$, which explains why non-linearity of the right kind, not just non-linearity, is needed. (iii) ReLU is unbounded and not sigmoidal, yet the theorem of Cybenko and Hornik still applies to it by a one-line reduction: $\rho(t)=\mathrm{ReLU}(t)-\mathrm{ReLU}(t-1)$ is continuous, bounded, non-decreasing and non-constant, and a network with $N$ units $\rho$ is a ReLU network with $2N$ units.
Exercise 1.1 · Step 1 of the proof, numerically
- Define the staircase $G_\lambda(t)=g(t_0)+\sum_{j=1}^{n}d_j\,\psi(\lambda(t-t_j))$ for $g(t)=\sin(2\pi t)+t/2$, with $\psi$ the logistic sigmoid.
- Measure the sup-norm error on a fine grid for $n\in\{10,40,160,640\}$ and $\lambda\in\{10^2,10^3,10^4,10^5\}$.
- Explain why increasing $\lambda$ alone does not make the error vanish.
# Cybenko, step 1 (dimension one): approximate g on [0, 1] by a sum of shifted, sharpened sigmoids.# Two things must grow together: the number of steps (a finer mesh) and the sharpness lam.def psi(t): return 1.0 / (1.0 + np.exp(-np.clip(t, -60, 60))) # sigmoid, clipped to avoid overflow in expg = lambda t: np.sin(2 * np.pi * t) + 0.5 * t # the function to approximatet = np.linspace(0, 1, 2001) # fine grid used to measure the sup-norm errordef staircase(n_steps, lam): knots = np.linspace(0, 1, n_steps + 1) # t_0 < ... < t_n d = ... # TO DO: increments d_j = g(t_j) - g(t_{j-1}) G = g(knots[0]) * np.ones_like(t) # constant term g(t_0) for j in range(1, n_steps + 1): G = ... # TO DO: add d_j * psi(lam * (t - t_j)) return Gfor n_steps in (10, 40, 160, 640): errs = ... # TO DO: sup error for each sharpness lam print(f"{n_steps:4d} steps: sup error for lam = 1e2, 1e3, 1e4, 1e5 ->", np.array(errs))plt.plot(t, g(t), "k", label="g")plt.plot(t, staircase(20, 1000), "C1", label="20 sigmoids, lam = 1000")plt.legend(); plt.title("Step 1 of the proof: a sum of sharpened sigmoids"); plt.show()

Show the correction
# Cybenko, step 1 (dimension one): approximate g on [0, 1] by a sum of shifted, sharpened sigmoids.# Two things must grow together: the number of steps (a finer mesh) and the sharpness lam.def psi(t): return 1.0 / (1.0 + np.exp(-np.clip(t, -60, 60))) # sigmoid, clipped to avoid overflow in expg = lambda t: np.sin(2 * np.pi * t) + 0.5 * t # the function to approximatet = np.linspace(0, 1, 2001) # fine grid used to measure the sup-norm errordef staircase(n_steps, lam): knots = np.linspace(0, 1, n_steps + 1) # t_0 < ... < t_n d = np.diff(g(knots)) # increments d_j = g(t_j) - g(t_{j-1}) G = g(knots[0]) * np.ones_like(t) # constant term g(t_0) for j in range(1, n_steps + 1): G = G + d[j - 1] * psi(lam * (t - knots[j])) # add d_j * psi(lam * (t - t_j)) return Gfor n_steps in (10, 40, 160, 640): errs = [np.max(np.abs(staircase(n_steps, lam) - g(t))) for lam in (100, 1000, 10000, 100000)] # sup error for each sharpness lam print(f"{n_steps:4d} steps: sup error for lam = 1e2, 1e3, 1e4, 1e5 ->", np.array(errs))plt.plot(t, g(t), "k", label="g")plt.plot(t, staircase(20, 1000), "C1", label="20 sigmoids, lam = 1000")plt.legend(); plt.title("Step 1 of the proof: a sum of sharpened sigmoids"); plt.show()
For a fixed number of steps $n$, the error is not monotone in $\lambda$: it is smallest for a moderate $\lambda$ (smooth transitions average $g$ over a cell) and then rises to a plateau, the maximal oscillation of $g$ on one cell of the true staircase, about $0.63,\,0.17,\,0.04,\,0.01$ for $n=10,40,160,640$ (a factor $4$ for each factor $4$ on $n$: the error is of order $1/n$). Only a finer mesh lowers the plateau, and a large $\lambda$ is needed only to make the transitions narrow compared to a cell. This is the two-step choice of the proof: first the mesh $\delta$, then $\lambda$ large. The number of neurons needed for accuracy $\varepsilon$ is of order $\mathrm{Lip}(g)/\varepsilon$ in dimension one; in dimension $m$ the same construction costs a power of $1/\varepsilon$ that grows with $m$.
Part 2 · How many neurons? Barron's rate
From existence to a rate
Density gives no information on the number $N$ of neurons. A classical obstacle: for a generic target in a Sobolev ball of smoothness $s$ in dimension $m$, any method that uses $N$ parameters in a reasonable way (continuously chosen) has worst-case error of order $N^{-s/m}$: the curse of dimensionality (lower bounds of this order are known under natural restrictions, for instance a continuous dependence of the parameters on $f$; see Pinkus 1999 and Maiorov–Pinkus 1999 for the exact statements and their restrictions). Barron’s theorem identifies a class of functions that escapes it.
For $f:\mathbb R^m\to\mathbb R$ with a Fourier representation $f(x)=\int e^{i\omega^{\top}x}\hat f(\omega)\,d\omega$, $\hat f\in L^1$, put $C_f=\int_{\mathbb R^m}\|\omega\|\,|\hat f(\omega)|\,d\omega$, the first absolute moment of the spectrum.
Let $f$ be real, with $C_f<\infty$, let $\mu$ be a probability measure on the ball $B_r=\{\|x\|\le r\}$ and $\phi$ a bounded sigmoidal function. For every $N\ge1$ there exist $c_0,c_i,b_i\in\mathbb R$ and $a_i\in\mathbb R^m$ such that
$$f_N(x)=c_0+\sum_{i=1}^{N}c_i\,\phi(a_i^{\top}x+b_i)\qquad\text{satisfies}\qquad\int_{B_r}\big(f(x)-f_N(x)\big)^2d\mu(x)\le\frac{(2rC_f)^2}{N}.$$Proof
Step 1: an integral representation. As $f$ is real, $\hat f(-\omega)=\overline{\hat f(\omega)}$ and, with $\hat f(\omega)=|\hat f(\omega)|e^{i\theta(\omega)}$, $f(x)=\int\cos(\omega^{\top}x+\theta(\omega))\,|\hat f(\omega)|\,d\omega$. Subtracting $f(0)$ and normalizing by the probability measure $\Lambda(d\omega)=\|\omega\|\,|\hat f(\omega)|\,d\omega/C_f$,
$$f(x)-f(0)=\int h_\omega(x)\,\Lambda(d\omega),\qquad h_\omega(x)=\frac{C_f}{\|\omega\|}\Big(\cos\big(\omega^{\top}x+\theta(\omega)\big)-\cos\theta(\omega)\Big).$$Step 2: each $h_\omega$ is a mixture of steps. $h_\omega(x)=k_\omega(u)$ with $u=\omega^{\top}x/\|\omega\|\in[-r,r]$ and $k_\omega(u)=\frac{C_f}{\|\omega\|}(\cos(\|\omega\|u+\theta)-\cos\theta)$, so $k_\omega(0)=0$ and $|k_\omega'|\le C_f$. Hence $k_\omega$ has total variation $V\le2rC_f$ on $[-r,r]$ and, integrating by parts, $k_\omega(u)=\int_0^r\mathbf 1[u\ge t]\,k_\omega'(t)\,dt-\int_{-r}^0\mathbf 1[u\le t]\,k_\omega'(t)\,dt$: a combination of step functions $\mathbf 1[a^{\top}x+b\ge0]$ of $\|a\|=1$ with coefficients of total weight $V$. Therefore $f-f(0)$ lies in the closure of the convex hull of $G=\{0\}\cup\{\pm B\,\mathbf 1[a^{\top}x+b\ge0]\}$ with $B=2rC_f$ (the function $0$ is a unit whose hyperplane misses the ball). Every element of $G$ has $L^2(\mu)$ norm at most $B$.
Step 3: sampling (Maurey–Jones–Barron lemma). Let $g_1,\dots,g_N$ be independent random elements of $G$ drawn according to the mixture that represents $g=f-f(0)$ (that is $E\,g_i=g$). Then $E\big\|g-\tfrac1N\sum g_i\big\|^2=\tfrac1N\big(E\|g_1\|^2-\|g\|^2\big)\le B^2/N$ because the $g_i-g$ are independent and centred in a Hilbert space. Some realization achieves the bound. Putting $c_0=f(0)$ and the $N$ steps gives a network with Heaviside units.
Step 4: from steps to $\phi$. $\phi(\lambda(a^{\top}x+b))\to\mathbf 1[a^{\top}x+b>0]$ pointwise off the hyperplane as $\lambda\to\infty$. Moving $b$ slightly so that $\mu$ gives no mass to the hyperplane (possible except for countably many values of $b$) and using dominated convergence, the sigmoidal network gets within any $\delta>0$ of the step network in $L^2(\mu)$; the slack $\|g\|^2$ lost in Step 3 absorbs $\delta$. $\square$
Interactive illustration. Compress a wide teacher network into a small student, in dimension 2 to 200.
# Barron / Maurey: compress a wide "teacher" network into N sampled units; the error decreases like C / sqrt(N) in any dimension.import numpy as npimport matplotlib.pyplot as pltsig = lambda z: 1 / (1 + np.exp(-np.clip(z, -60, 60)))K, C = 300, 3.0 # teacher: K units, sum |c_i| = Cdef teacher(d, rng): U = rng.normal(size=(K, d)); U = 5 * U / np.linalg.norm(U, axis=1, keepdims=True) b = rng.uniform(-3, 3, K) c = rng.normal(size=K); c = C * c / np.abs(c).sum() X = rng.normal(size=(300, d)); X *= (rng.uniform(size=(300, 1)) ** (1 / d)) / np.linalg.norm(X, axis=1, keepdims=True) # points in the unit ball H = sig(X @ U.T + b) # hidden outputs: 300 x K return H, cdef student_error(H, c, N, rng, trials=14): p = np.abs(c) / np.abs(c).sum() errs = [] for _ in range(trials): i = rng.choice(K, size=N, p=p) # sample N units with probability |c_i| / C fN = (np.sign(c[i]) * C / N) @ H[:, i].T # weights +-C/N errs.append(np.mean((H @ c - fN) ** 2)) return np.sqrt(np.mean(errs))rng = np.random.default_rng(0)Ns = 2 ** np.arange(9)for d in (2, 10, 50, 200): H, c = teacher(d, rng) e = [student_error(H, c, N, rng) for N in Ns] plt.loglog(Ns, e, "o-", label=f"d = {d}") print(f"d = {d:3d}: error for N = 16, 256: {e[4]:.3f}, {e[8]:.3f}, ratio {e[4] / e[8]:.1f} (theory: 4)")plt.loglog(Ns, C / np.sqrt(Ns), "k--", label="C / sqrt(N)")plt.xlabel("N"); plt.ylabel("RMS error"); plt.legend(); plt.title("the rate does not depend on the dimension"); plt.show()
What the theorem gives. A rate $N^{-1/2}$ in $L^2$ that does not contain the dimension $m$ in the exponent, and the explicit weights $\sum_i|c_i|\le2rC_f$ (bounded total weight, in the spirit of $\ell^1$ regularization). By contrast, Barron also proves that any fixed $N$-dimensional linear space (polynomials, splines, a fixed basis of features) has a worst-case error of order $N^{-1/m}$ on the same class: the neural network wins because it chooses its features $a_i,b_i$ in a way adapted to $f$.
Limits. (i) The dimension is hidden in the constant: $C_f$ can grow exponentially in $m$ (for instance for a smooth bump of fixed width localized in $m$ variables); the class $\{C_f\le C\}$ is not “all smooth functions”. (ii) The proof is a random choice of neurons: it does not describe an algorithm, and gradient descent is not shown to find such weights. (iii) $L^2(\mu)$ on a ball, not the uniform norm. (iv) Only one hidden layer: for deeper networks the corresponding approximation classes are less understood, and the next part shows that depth can change the picture completely.
Part 3 · Why depth: counting linear pieces
Counting the linear pieces of a ReLU network
With ReLU, a network $\mathbb R\to\mathbb R$ is a continuous piecewise-linear function. Its number of linear pieces measures its expressive power, and it is easy to bound.
A ReLU network $\mathbb R\to\mathbb R$ with $L$ hidden layers of widths $m_1,\dots,m_L$ computes a piecewise-linear function with at most $\prod_{l=1}^{L}(m_l+1)$ pieces. In particular a one-hidden-layer network with $m$ units has at most $m+1$ pieces.
Proof
Induction on the layers. Before the first layer the input $x$ is affine on one piece. Suppose the vector of outputs of layer $l-1$ is affine on each of $p$ intervals (a common subdivision). The pre-activation of a unit of layer $l$ is then affine on each of these intervals, so it has at most one zero on each, and $\mathrm{ReLU}$ of it creates at most one breakpoint per interval. With $m_l$ units, each of the $p$ intervals is cut into at most $m_l+1$ pieces, and the output vector of layer $l$ is affine on each of them. The last (linear) layer adds none. $\square$
Interactive illustration. How finely can a ReLU network cut a one-dimensional input?
# Counting the linear pieces of a ReLU network R -> R on [0, 1].import numpy as npimport matplotlib.pyplot as pltrelu = lambda z: np.maximum(z, 0)n = 20000grid = np.linspace(0, 1, n + 1)def zigzag(u, m): """One layer of m units relu(u - i/m): a zigzag with m pieces that maps [0, 1] onto [0, 1].""" c = np.array([m] + [2 * m * (-1) ** i for i in range(1, m)], dtype=float) # slopes +m, -m, +m, ... return relu(u[:, None] - np.arange(m) / m) @ cdef random_layer(u, m, rng): w = rng.choice([-1, 1], m) * (1 + 2 * rng.uniform(size=m)) # random slopes t = rng.uniform(0, 1, m) # kinks inside the range of u out = relu(w * u[:, None] - w * t) @ rng.normal(size=m) return (out - out.min()) / (out.max() - out.min()) # an affine map: absorbed by the next layerdef pieces(u): slopes = np.diff(u) * n changed = np.abs(np.diff(slopes)) > 1e-6 * (1 + np.abs(slopes[:-1])) return 1 + np.sum(changed[1:] & ~changed[:-1]) + int(changed[0]) # one kink = one run of changed cellsm = 2rng = np.random.default_rng(1)print("L | bound (m+1)^L | zigzag m^L | zigzag counted | random weights (mean of 12) | one hidden layer, same neurons")for L in range(1, 7): u = grid for _ in range(L): u = zigzag(u, m) rnd = [] for _ in range(12): v = grid for _ in range(L): v = random_layer(v, m, rng) rnd.append(pieces(v)) print(f"{L} | {(m + 1) ** L:13d} | {m ** L:10d} | {pieces(u):14d} | {np.mean(rnd):27.1f} | {L * m + 1}")u = gridfor _ in range(3): u = zigzag(u, m)plt.plot(grid, u); plt.title("3 layers of width 2: 2^3 = 8 pieces"); plt.show()
The tent map $T(x)=2\,\mathrm{ReLU}(x)-4\,\mathrm{ReLU}(x-\tfrac12)$ sends $[0,1]$ to $[0,1]$ ($T=2x$ on $[0,\frac12]$, $2-2x$ on $[\frac12,1]$) and is computed by two units. Its $k$-fold composition $s_k=T\circ\cdots\circ T$ is the sawtooth: it is computed by a network of depth $k$ and width $2$.
$s_k$ has exactly $2^k$ linear pieces, each of slope $\pm2^k$. It is computed exactly by a ReLU network of depth $k$ and width $2$ ($2k$ units), whereas a ReLU network with a single hidden layer needs at least $2^k-1$ units to compute it, and a network of depth $L$ and width $m$ needs $(m+1)^L\ge2^k$, i.e. $L\ge k/\log_2(m+1)$.
Proof
On $[0,\frac12]$, $s_k(x)=s_{k-1}(2x)$ and on $[\frac12,1]$, $s_k(x)=s_{k-1}(2-2x)$; by induction $s_k$ has $2\cdot2^{k-1}$ pieces of slope $\pm2\cdot2^{k-1}$, and neighbouring pieces have opposite slopes, so every junction is a true breakpoint. The depth-$k$, width-2 network is obtained by stacking $k$ copies of the two-unit block (the output of a block, which is $\ge0$, is fed to the next, and $\mathrm{ReLU}$ leaves it unchanged where needed). By the lemma, $m$ units in one hidden layer give at most $m+1$ pieces, so $m+1\ge2^k$. $\square$
Interactive illustration. A classification problem whose labels alternate $2^k$ times.
# Depth separation: the sawtooth s_k (k layers, 2k neurons) against one hidden layer with N units.import numpy as npimport matplotlib.pyplot as pltrelu = lambda z: np.maximum(z, 0)tent = lambda u: 2 * relu(u) - 4 * relu(u - 0.5) # two ReLU unitsdef sawtooth(x, k): for _ in range(k): x = tent(x) return xx = np.linspace(0, 1, 513)def shallow_fit(k, N): A = np.column_stack([np.ones_like(x)] + [relu(x - j / N) for j in range(N)]) # N ReLU units at uniform knots + output bias coef, *_ = np.linalg.lstsq(A, sawtooth(x, k), rcond=None) return A @ coefk = 5print(f"s_{k}: {2 ** k} pieces, computed exactly with {2 * k} neurons in {k} layers")for N in (2 * k, 16, 31, 32, 64): fit = shallow_fit(k, N) s = sawtooth(x, k) mask = np.abs(s - 0.5) > 1e-6 acc = np.mean((fit[mask] > 0.5) == (s[mask] > 0.5)) print(f"one hidden layer, N = {N:2d}: sup error {np.max(np.abs(fit - s)):.2e}, labels (s_k > 1/2) correct: {100 * acc:.0f} %")fig, ax = plt.subplots(1, 2, figsize=(11, 3.6))ax[0].plot(x, sawtooth(x, k), "k", label=f"s_{k}, {2 * k} neurons"); ax[0].plot(x, shallow_fit(k, 2 * k), "C1", label=f"1 hidden layer, N = {2 * k}")ax[0].legend()Ns = [1, 2, 3, 4, 6, 8, 12, 16, 24, 32, 48, 64]ax[1].semilogy(Ns, [max(np.max(np.abs(shallow_fit(k, N) - sawtooth(x, k))), 1e-16) for N in Ns], "o-")ax[1].axvline(2 ** k, color="r", ls="--"); ax[1].set_xlabel("N"); ax[1].set_ylabel("sup error"); plt.show()
The proposition is about exact representation. Telgarsky (2016) proves a robust version: functions computed with depth of order $k^3$ and constant width cannot be approximated, in $L^1$, by networks of depth of order $k$ unless they have $\Omega(2^k)$ units, because the oscillations of $s_k$ cannot be matched by fewer pieces. Eldan and Shamir (2016) show another kind of separation without piecewise linearity: a radial function of the form $\psi(\|x\|^2)$ on $\mathbb R^m$ is computed by a network with two hidden layers and a number of units polynomial in $m$, but any one-hidden-layer network that approximates it to constant accuracy (in $L^2$, for a specific input distribution) needs a number of units exponential in $m$. (Statements recalled here without proof.)
Limits. The separating functions are special (highly oscillating or radial); Safran, Eldan and Shamir (2021) show that such separations depend on the input distribution. The theorems do not say that real targets, such as images, are of this kind, nor that deep networks learn these representations.
Exercise 3.1 · Build the sawtooth with Keras and count the pieces
- Build, with fixed weights, a ReLU network of depth $k$ and width 2 that computes $s_k$, for $k=1,\dots,6$.
- Count its linear pieces on a fine grid and compare with $2^k$.
- Train a one-hidden-layer network with 16 units to fit $s_5$ and measure the error.
# Depth versus width: the sawtooth s_k = T o ... o T (k times), with the tent map T(x) = 2 ReLU(x) - 4 ReLU(x - 1/2) on [0, 1].def deep_sawtooth(k): """ReLU network of depth k and width 2 whose output is the k-fold tent map.""" m = keras.Sequential([keras.Input((1,))]) first = layers.Dense(2, activation="relu") m.add(first) first.set_weights([np.array([[1.0, 1.0]]), np.array([0.0, -0.5])]) # (ReLU(x), ReLU(x - 1/2)) for _ in range(k - 1): h = layers.Dense(2, activation="relu") m.add(h) ... # TO DO: weights that recompute (T, T - 1/2) from the previous pair out = layers.Dense(1) m.add(out) out.set_weights([np.array([[2.0], [-4.0]]), np.array([0.0])]) # T = 2a - 4b return mx = np.linspace(0, 1, 2 ** 14 + 1)[:, None] # grid whose step divides every breakpointdef n_pieces(f, tol=1e-6): slope = np.diff(f.ravel()) / np.diff(x.ravel()) return ... # TO DO: pieces = 1 + number of slope changesfor k in range(1, 7): net = deep_sawtooth(k) y = net.predict(x, verbose=0) print(f"depth {k}, width 2 ({net.count_params()} parameters): {n_pieces(y)} linear pieces (2^k = {2 ** k})")# A shallow net with N hidden units has at most N + 1 pieces: try to fit s_5 (32 pieces) with 16 units.target = deep_sawtooth(5).predict(x, verbose=0)shallow = keras.Sequential([keras.Input((1,)), layers.Dense(16, activation="relu"), layers.Dense(1)])shallow.compile(optimizer=keras.optimizers.Adam(0.003), loss="mse")... # TO DO: train the shallow net on a subsample of the gridfit = shallow.predict(x, verbose=0)print("shallow net, 16 units (at most 17 pieces): max error", round(float(np.max(np.abs(fit - target))), 3), "| mean error", round(float(np.mean(np.abs(fit - target))), 3))plt.plot(x, target, "k", label="s_5, depth 5 width 2")plt.plot(x, fit, "C1", label="best shallow fit, 16 units")plt.legend(); plt.title("Depth gives exponentially many pieces"); plt.show()

Show the correction
# Depth versus width: the sawtooth s_k = T o ... o T (k times), with the tent map T(x) = 2 ReLU(x) - 4 ReLU(x - 1/2) on [0, 1].def deep_sawtooth(k): """ReLU network of depth k and width 2 whose output is the k-fold tent map.""" m = keras.Sequential([keras.Input((1,))]) first = layers.Dense(2, activation="relu") m.add(first) first.set_weights([np.array([[1.0, 1.0]]), np.array([0.0, -0.5])]) # (ReLU(x), ReLU(x - 1/2)) for _ in range(k - 1): h = layers.Dense(2, activation="relu") m.add(h) h.set_weights([np.array([[2.0, 2.0], [-4.0, -4.0]]), np.array([0.0, -0.5])]) # weights that recompute (T, T - 1/2) from the previous pair out = layers.Dense(1) m.add(out) out.set_weights([np.array([[2.0], [-4.0]]), np.array([0.0])]) # T = 2a - 4b return mx = np.linspace(0, 1, 2 ** 14 + 1)[:, None] # grid whose step divides every breakpointdef n_pieces(f, tol=1e-6): slope = np.diff(f.ravel()) / np.diff(x.ravel()) return 1 + int(np.sum(np.abs(np.diff(slope)) > tol)) # pieces = 1 + number of slope changesfor k in range(1, 7): net = deep_sawtooth(k) y = net.predict(x, verbose=0) print(f"depth {k}, width 2 ({net.count_params()} parameters): {n_pieces(y)} linear pieces (2^k = {2 ** k})")# A shallow net with N hidden units has at most N + 1 pieces: try to fit s_5 (32 pieces) with 16 units.target = deep_sawtooth(5).predict(x, verbose=0)shallow = keras.Sequential([keras.Input((1,)), layers.Dense(16, activation="relu"), layers.Dense(1)])shallow.compile(optimizer=keras.optimizers.Adam(0.003), loss="mse")shallow.fit(x[::8], target[::8], epochs=800, batch_size=64, verbose=0) # train the shallow net on a subsample of the gridfit = shallow.predict(x, verbose=0)print("shallow net, 16 units (at most 17 pieces): max error", round(float(np.max(np.abs(fit - target))), 3), "| mean error", round(float(np.mean(np.abs(fit - target))), 3))plt.plot(x, target, "k", label="s_5, depth 5 width 2")plt.plot(x, fit, "C1", label="best shallow fit, 16 units")plt.legend(); plt.title("Depth gives exponentially many pieces"); plt.show()
The deep network has $2k$ units and $2^k$ pieces: $64$ pieces with $12$ units for $k=6$. A shallow network with $16$ units has at most $17$ pieces, so it cannot follow the $32$ oscillations of $s_5$. In our run the training stays near the mean value of $s_5$ (mean error about $0.25$, maximal error about $0.5$): the bound of the lemma is a necessary obstruction, and gradient descent adds its own difficulty (this fit is hard to optimize even for the available $17$ pieces). Do not read the printed error as a measure of the best shallow approximation; read it as an illustration.
Part 4 · Bounded width and arbitrary depth
The dual question: bounded width, arbitrary depth
Cybenko’s theorem lets the width grow with the accuracy. The dual question: how narrow can a deep network be and still be universal? Let $n$ be the input dimension and $m$ the output dimension.
A ReLU network $\mathbb R\to\mathbb R$ whose hidden layers all have width $1$ is monotone. It cannot approximate uniformly on $[0,1]$ a non-monotone function such as $f(x)=x(1-x)$ with an error below $\tfrac18$.
Proof
Each hidden unit computes $u\mapsto\mathrm{ReLU}(au+b)$, which is monotone, and the output is an affine function of the last unit. A composition of monotone functions is monotone, so the network $h$ is monotone. If $h$ is non-decreasing, $h(1)\ge h(\tfrac12)$; if both $|h(\tfrac12)-\tfrac14|$ and $|h(1)|$ were below $\tfrac18$ we would have $h(1)<\tfrac18<h(\tfrac12)$, a contradiction, so $\|h-f\|_\infty\ge\tfrac18$. If $h$ is non-increasing, use $h(0)\ge h(\tfrac12)$ in the same way. $\square$
Interactive illustration. Train narrow ReLU networks live, in one and in two dimensions.
# Width: a ReLU network of width n cannot make a bump in R^n, width n + 1 can (Hanin-Sellke).import numpy as npimport matplotlib.pyplot as pltdef init(sizes, rng): return [[rng.normal(size=(a, b)) * np.sqrt(2 / a), np.full(b, 0.2) if i < len(sizes) - 2 else np.zeros(b)] for i, (a, b) in enumerate(zip(sizes[:-1], sizes[1:]))]def forward(params, X): acts = [X] for i, (W, b) in enumerate(params): z = acts[-1] @ W + b acts.append(np.maximum(z, 0) if i < len(params) - 1 else z) return actsdef train(params, X, y, epochs, lr): # full-batch Adam, mean squared error m = [[np.zeros_like(p) for p in layer] for layer in params]; v = [[np.zeros_like(p) for p in layer] for layer in params] for t in range(1, epochs + 1): acts = forward(params, X) delta = 2 * (acts[-1][:, 0] - y)[:, None] / len(X) for i in reversed(range(len(params))): grads = [acts[i].T @ delta, delta.sum(axis=0)] delta = (delta @ params[i][0].T) * (acts[i] > 0) if i > 0 else None for j in range(2): m[i][j] = 0.9 * m[i][j] + 0.1 * grads[j]; v[i][j] = 0.999 * v[i][j] + 0.001 * grads[j] ** 2 params[i][j] -= lr * (m[i][j] / (1 - 0.9 ** t)) / (np.sqrt(v[i][j] / (1 - 0.999 ** t)) + 1e-8) return params# 1D: f(x) = x (1 - x). A width-1 network is monotone: its uniform error is at least 1/8.x = np.linspace(0, 1, 81)[:, None]; target = (x * (1 - x))[:, 0]for width in (1, 2): best = min(np.max(np.abs(forward(train(init([1] + [width] * 4 + [1], np.random.default_rng(s)), x, target, 1500, 0.02), x)[-1][:, 0] - target)) for s in range(10)) print(f"1D, width {width}: best uniform error over 10 restarts = {best:.3f} (1/8 = 0.125)")# 2D: a bump f(x) = max(0, 1 - |x| / 0.6). Width 2 = n cannot, width 3 = n + 1 can.rng = np.random.default_rng(5)bump = lambda P: np.maximum(0, 1 - np.linalg.norm(P, axis=1) / 0.6)X = rng.uniform(-1, 1, (300, 2)); g = np.linspace(-1, 1, 41); T = np.array([[a, b] for a in g for b in g])for width in (2, 3): errs = [] for s in range(1, 7): net = train(init([2] + [width] * 5 + [1], np.random.default_rng(s)), X, bump(X), 2500, 0.01) errs.append(np.max(np.abs(forward(net, T)[-1][:, 0] - bump(T)))) print(f"2D, width {width}: uniform error for 6 seeds:", np.round(errs, 2))net = train(init([2] + [3] * 5 + [1], np.random.default_rng(2)), X, bump(X), 2500, 0.01)plt.contourf(g, g, forward(net, T)[-1][:, 0].reshape(41, 41).T, 20); plt.contour(g, g, bump(T).reshape(41, 41).T, [0.5], colors="k", linestyles="--")plt.title("width 3: the level set F = 1/2 closes (dashed: target)"); plt.show()
Width $2$ is enough for continuous functions of one variable, and $n+1$ for $n$ variables (Hanin–Sellke, table below): a unit that carries the input and one that accumulates the work. In dimension $n$ the obstruction generalizes: with all hidden layers of width $\le n$ the network cannot approximate every continuous function. The precise results:
| Result | Setting | Minimal width | Comment |
|---|---|---|---|
| Lu, Pu, Wang, Hu, Wang (2017) | ReLU, $L^1(\mathbb R^n)\to\mathbb R$ | $n+4$ suffices; $n$ does not | first universal-width result; $n+4$ units: $n$ carry the input, a few more compute the next local piece and accumulate the sum |
| Hanin, Sellke (2017) | ReLU, $\mathcal C(K,\mathbb R^m)$, $K\subset\mathbb R^n$ compact, uniform norm | $n+1\le w_{\min}\le n+m$; for $m=1$: exactly $n+1$ | lower bound: with width $\le n$ the level sets $\{F=c\}$ have no bounded connected component, so a function with a compact level component (a bump) is not approximable |
| Kidger, Lyons (2020) | $\mathcal C(K,\mathbb R^m)$, general non-affine continuous activation, $\mathcal C^1$ at one point with non-zero derivative | $n+m+2$ suffices | covers $\tanh$, sigmoid, softplus…; width independent of the accuracy, depth grows |
| Park, Yun, Lee, Shin (2021) | ReLU, $L^p(\mathbb R^n,\mathbb R^m)$, $1\le p<\infty$ | exactly $\max(n+1,m)$ | sharp; for the uniform norm the exact value can differ from the $L^p$ one |
Differences with Part 1. Part 1 fixes the depth (one hidden layer) and lets the width diverge; Part 4 fixes the width ($\approx n+1$) and lets the depth diverge. Both are density statements: the other quantity is unbounded and not estimated. The lower bound $n+1$ is a genuine geometric obstruction (the network must be able to carry its input and one scalar of work), whereas the upper bounds come from constructions that emulate piecewise-linear or local approximants and are very inefficient. The results of this part do not imply that a network of width $n+1$ is a good model in practice; they say that its class is not too small.
Part 5 · Beyond the dense MLP: operators, convolutions, attention
Operators: Chen–Chen and DeepONet
Let $\phi$ be continuous and not a polynomial, $K_1\subset\mathbb R^p$, $K_2\subset\mathbb R^q$ compact, $V\subset\mathcal C(K_1)$ compact and $\mathcal G:V\to\mathcal C(K_2)$ a continuous operator. For every $\varepsilon>0$ there exist integers $N,M,P$, points $x_1,\dots,x_P\in K_1$ (the sensors) and reals $c_i^k,\xi_{ij}^k,\theta_i^k,\zeta_k$, vectors $w_k$ such that for all $u\in V$, $y\in K_2$,
$$\Big|\mathcal G(u)(y)-\sum_{k=1}^{N}\underbrace{\Big(\sum_{i=1}^{M}c_i^k\,\phi\Big(\sum_{j=1}^{P}\xi_{ij}^k\,u(x_j)+\theta_i^k\Big)\Big)}_{\text{branch: depends on }u}\;\underbrace{\phi(w_k^{\top}y+\zeta_k)}_{\text{trunk: depends on }y}\Big|<\varepsilon .$$Proof
Outline. (1) Sensors. $V$ is compact in $\mathcal C(K_1)$, hence equicontinuous: for $P$ large and well-placed sensors, every $u\in V$ is within a small uniform distance of its piecewise-linear interpolant built from $(u(x_j))_j$; by continuity and compactness, $\mathcal G(u)$ is within $\varepsilon/3$ of $\mathcal G$ applied to this interpolant, a continuous function $\Gamma(u(x_1),\dots,u(x_P);y)$ of finitely many variables. (2) Variable $y$. For fixed sensor values, apply Part 1 in $y$ and keep track of the dependence of the coefficients on the sensor values: this gives $\sum_kb_k(u(x_1),\dots,u(x_P))\,\phi(w_k^{\top}y+\zeta_k)$ with continuous coefficient functions $b_k$ (a partition-of-unity argument makes the $b_k$ continuous). (3) Coefficients. Approximate each $b_k$ on the compact set of sensor vectors by a one-hidden-layer network (Part 1). The three errors add to $\varepsilon$. This is an outline: the compactness and partition-of-unity details are not reproduced. $\square$
Interactive illustration. A surrogate for an operator: from a function sampled at $P$ sensors to another function.
# Chen-Chen: learn the operator u -> antiderivative of u from P sensor values, with a branch x trunk network.import numpy as npimport matplotlib.pyplot as pltrng = np.random.default_rng(33)P, M, Kt, S = 10, 24, 16, 400 # sensors, branch units, trunk units, training functionssensors = np.linspace(0, 1, P)ys = np.linspace(0, 1, 20)def coefficients(r): # u(x) = sum_k a_k cos(k pi x), a_k ~ N(0, 1/(1+k)^2) return r.normal(size=6) / (1 + np.arange(6))u = lambda a, x: np.cos(np.pi * np.outer(np.atleast_1d(x), np.arange(6))) @ adef G(a, y): # exact antiderivative of u k = np.arange(1, 6) return a[0] * y + np.sin(np.pi * np.outer(np.atleast_1d(y), k)) @ (a[1:] / (np.pi * k))xi = 0.1 * rng.normal(size=(P, M)) / np.sqrt(P); theta = 0.7 * rng.normal(size=M) # random inner weights of the branchom, ze = 3 * rng.normal(size=Kt), 1.5 * rng.normal(size=Kt) # random inner weights of the trunkbranch = lambda a: np.tanh(u(a, sensors) @ xi + theta) # depends on u only through its sensorstrunk = lambda y: np.tanh(np.outer(y, om) + ze)r = np.random.default_rng(21)train = [coefficients(r) for _ in range(S)]B = np.array([branch(a) for a in train]) # S x MGm = np.array([G(a, ys) for a in train]) # S x 20T = trunk(ys) # 20 x Ktlam = 1e-8C = np.linalg.solve(B.T @ B + lam * S * np.eye(M), B.T @ Gm @ T) @ np.linalg.inv(T.T @ T + lam * len(ys) * np.eye(Kt)) # least squares for the output weights c_ikrt = np.random.default_rng(999)tests = [coefficients(rt) for _ in range(40)]predict = lambda a, y: branch(a) @ C @ trunk(y).T # sum_ik c_ik branch_i(u) trunk_k(y)yy = np.linspace(0, 1, 101)err = np.sqrt(sum(np.sum((G(a, yy) - predict(a, yy)) ** 2) for a in tests) / sum(np.sum(G(a, yy) ** 2) for a in tests))print(f"relative L2 error on 40 new input functions: {100 * err:.2f} % ({M * Kt} output weights fitted)")a = tests[0]fig, ax = plt.subplots(1, 2, figsize=(10, 3.5))ax[0].plot(yy, u(a, yy), "k"); ax[0].plot(sensors, u(a, sensors), "o"); ax[0].set_title("input u and its sensors")ax[1].plot(yy, G(a, yy), "k", label="exact"); ax[1].plot(yy, predict(a, yy), "C1", label="network"); ax[1].legend(); ax[1].set_title("output G(u)"); plt.show()
Lu, Jin, Pang, Zhang, Karniadakis (2021, DeepONet) turn the statement into an architecture: a branch network encodes the sampled input function, a trunk network encodes the query point, and the output is their scalar product. Limits: the sensors are fixed and the result is about compact $V$; no bound on $N,M,P$.
Convolutional networks: Zhou (2020)
Let $\Omega\subset[-1,1]^d$ be compact. For every $f\in\mathcal C(\Omega)$ and $\varepsilon>0$ there is a deep one-dimensional convolutional network with ReLU activation, with short convolution filters (of bounded length), whose output is within $\varepsilon$ of $f$ uniformly on $\Omega$. The depth grows as $\varepsilon\to0$.
Proof
Outline. By Part 1 with ReLU, $f$ is approximated by a one-hidden-layer network, whose first layer is a dense $N\times d$ matrix. The key lemma is that a dense matrix (of the appropriate size and after padding with zeros) can be written as a product of a large number of banded Toeplitz matrices, i.e. as a composition of convolutions with short filters. The ReLUs of the dense hidden layer are then inserted between these factors, and the extra convolutional layers carry the intermediate values unchanged (possible for ReLU on a bounded domain). The proof of the factorization is the technical heart of the paper and is not reproduced here. $\square$
Interactive illustration. How deep must a stack of short convolutions be to see a whole signal?
# Zhou: a stack of short convolutions sees farther and farther: receptive field = layers * (s - 1) + 1.import numpy as npimport matplotlib.pyplot as pltd, s, L = 48, 3, 4 # signal length, filter length, layersrng = np.random.default_rng(1)def toeplitz(w, d): """Matrix of the zero-padded 'same' convolution with the filter w.""" T = np.zeros((d, d)); off = (len(w) - 1) // 2 for i in range(d): for r, wr in enumerate(w): if 0 <= i + r - off < d: T[i, i + r - off] = wr return Tfilters = [1 / s + 0.6 * rng.normal(size=s) / np.sqrt(s) for _ in range(L)]J = np.eye(d)for w in filters: J = toeplitz(w, d) @ J # the Jacobian of the linear stack (no ReLU: a product of banded matrices)pos = 20print(f"layers = {L}, s = {s}: nonzero entries of row {pos}:", np.sum(np.abs(J[pos]) > 1e-12), " theory L(s-1)+1 =", L * (s - 1) + 1)print("layers needed for an edge output to see the whole input: ceil((d-1)/(s-1)) =", int(np.ceil((d - 1) / (s - 1))))plt.imshow(np.log10(np.abs(J) + 1e-12), cmap="Blues", vmin=-4); plt.xlabel("input j"); plt.ylabel("output i")plt.title("|Jacobian| of 4 convolutions: a band of width 9"); plt.colorbar(); plt.show()
Differences and limits. The theorem says that locality of the filters, sparsity and weight sharing do not destroy universality, because depth compensates. It is not a statement on the advantage of CNNs: it does not use the translation structure of images (no equivariance is claimed), and the depth needed grows quickly with the accuracy.
Transformers: Yun et al. (2020)
Let $f$ be a continuous map from sequences $X\in[0,1]^{d\times n}$ (compact domain, $n$ tokens) to sequences in $\mathbb R^{d\times n}$ that is permutation-equivariant. For every $p\in[1,\infty)$ and $\varepsilon>0$ there is a Transformer (self-attention blocks with softmax attention, each followed by a position-wise ReLU network, with a small number of heads and hidden units) with $\|f-g\|_{L^p}<\varepsilon$. With positional encodings, the same holds for every continuous sequence-to-sequence function, not only the equivariant ones.
Proof
Outline. (1) Quantization: a piecewise-constant function on a fine grid of the input cube is $\varepsilon$-close to $f$ in $L^p$; it suffices to realize it on the grid points, up to a set of small measure. (2) Contextual mapping: a stack of self-attention layers, with large weights so that softmax behaves like a hardmax (selecting the largest or smallest coordinate along a direction), computes a contextual mapping, a function that gives to every pair (sequence, token) a code that is distinct from all other pairs. (3) Token-wise readout: position-wise feed-forward layers map each code to the desired output, as in a lookup table. The permutation-equivariance of the attention layer without positional encoding explains the first case; positional encodings break the symmetry. This is an outline: the construction of the contextual mapping is long and not reproduced. $\square$
Interactive illustration. The same word in two contexts, and a shuffle of the tokens.
# Attention: permutation-equivariant, and context-dependent ("bank" in two contexts).import numpy as npimport matplotlib.pyplot as pltemb = {"river": (-1.0, 0.6), "water": (-0.8, 1.0), "bank": (0.0, 0.9), "money": (1.0, 0.6), "loan": (0.8, 1.0)}beta = 2.0def attention_layer(X): scores = beta * X @ X.T # q_i . k_j with W_Q = W_K = identity A = np.exp(scores - scores.max(axis=1, keepdims=True)); A /= A.sum(axis=1, keepdims=True) # softmax over the tokens j return (X + A @ X) / 2, A # residual connection + attention averagesentence = lambda words: np.array([emb[w] for w in words])A_ctx, B_ctx = sentence(["river", "water", "bank"]), sentence(["money", "loan", "bank"])YA, attn = attention_layer(A_ctx)YB, _ = attention_layer(B_ctx)print("attention weights, context A (rows: river, water, bank):\n", attn.round(2))print("'bank' before:", A_ctx[2], " after, context A:", YA[2].round(3), " after, context B:", YB[2].round(3))perm = np.array([1, 2, 0]) # shuffle the tokensY_shuffled, _ = attention_layer(A_ctx[perm])print("equivariance: max |layer(shuffled input) - shuffled layer(input)| =", np.max(np.abs(Y_shuffled - YA[perm])))for X, Y, c in ((A_ctx, YA, "C0"), (B_ctx, YB, "C1")): for x, y in zip(X, Y): plt.annotate("", xy=y, xytext=x, arrowprops=dict(arrowstyle="->", color=c)); plt.plot(*x, "o", color=c)for w, p in emb.items(): plt.text(p[0], p[1] + 0.05, w)plt.title("tokens move according to their context"); plt.show()
Limits. The norm is $L^p$, not uniform; the construction needs a number of layers that is huge (exponential in the sequence length and dimension for the original construction), and it uses a hardmax regime that trained attention does not follow.
Filippov networks: universality with hard routing
Recall (Filippov neural networks with Keras): a switching operator is an operator $\Phi:\Omega\to\mathbb R^m$ such that $\Omega\subset\mathbb R^n$ is covered, up to a null set $\Sigma$, by disjoint open regions $\Omega^{(k)}$ on each of which $\Phi$ coincides with a $C^1$ branch $\Phi^{(k)}$; $J(x)=\{k:x\in\overline{\Omega^{(k)}}\}$ is the active index set and the Filippov set is $\mathcal F[\Phi](x)=\operatorname{co}\{\Phi^{(k)}(x):k\in J(x)\}$. A Filippov network is a directed acyclic graph of such operators (affine nodes, ReLU, max-pooling, hard-routed blocks). The network used below has one router and ReLU experts: with centres $c_1,\dots,c_M\in\mathbb R^n$ and scores $s_j(x)=2c_j^{\top}x-\|c_j\|^2$, put $r(x)\in\arg\max_js_j(x)$ and $\Phi(x)=E_{r(x)}(x)$, each $E_k$ a ReLU network. The regions $\{r=k\}$ are the Voronoi cells of the centres: their boundaries lie in a finite union of hyperplanes, a null set.
Let $K\subset\mathbb R^n$ be compact.
- Continuous targets, routing only. For every $f\in C(K;\mathbb R^m)$ and $\varepsilon>0$ there is a hard router with finitely many centres and constant experts such that $\sup_{x\in K}\|f(x)-\Phi(x)\|<\varepsilon$, at every point of $K$, ties included.
- Discontinuous targets. Let $c_1,\dots,c_M$ be distinct centres, $\Omega=\mathrm{int}\,K$, where $\Omega_k=\Omega\cap\{x:\ s_k(x)>s_j(x)\ \forall j\ne k\}$ is an open Voronoi cell; let $f:K\to\mathbb R^m$ be such that $f|_{\Omega_k}$ extends to a continuous function $f_k$ on $\overline{\Omega_k}$ (the branches $f_k$ may disagree on the interfaces) and call $\mathcal F[f](x)=\operatorname{co}\{f_k(x):k\in J(x)\}$ its Filippov set, as in the course when the branches are $C^1$. Then for every $\varepsilon>0$ there are ReLU networks $E_1,\dots,E_M$ such that the Filippov network $\Phi=E_{r(x)}(x)$ satisfies (i) $\|f(x)-\Phi(x)\|\le\varepsilon$ for all $x\in\bigcup_k\Omega_k$, that is, off the router boundaries; (ii) at every $x\in\Omega$, $\mathcal F[\Phi](x)=\operatorname{co}\{E_k(x):k\in J(x)\}$ and the Hausdorff distance between $\mathcal F[\Phi](x)$ and $\mathcal F[f](x)$ is at most $\varepsilon$.
- Routing is necessary. If $f$ has oscillation $\omega>0$ at some point $x_0$ (that is, $\lim_{r\to0}\operatorname{diam}f(B(x_0,r)\cap K)=\omega$), then every continuous $G:K\to\mathbb R^m$, in particular every ReLU network, satisfies $\sup_K\|f-G\|\ge\omega/2$.
Proof
(a) $f$ is uniformly continuous on $K$, with modulus $\varpi$. Let $h>0$ with $\varpi(h\sqrt n)<\varepsilon$ and let $C=h\mathbb Z^n\cap\{y:\operatorname{dist}(y,K)\le h\sqrt n\}$, a finite set of centres. For each $c\in C$ choose $p_c\in K$ closest to $c$ and take the constant expert $E_c=f(p_c)$. Let $x\in K$ and $c=c_{r(x)}$ the centre selected by the router (any one in case of tie): it is a nearest centre of $x$ in $C$, so $\|x-c\|\le h\sqrt n/2$ (the nearest point of $h\mathbb Z^n$ to $x$ is in $C$). Then $\|c-p_c\|\le\|c-x\|$ because $x\in K$, so $\|x-p_c\|\le h\sqrt n$ and $\|f(x)-\Phi(x)\|=\|f(x)-f(p_c)\|\le\varpi(h\sqrt n)<\varepsilon$. The scores are affine, and $\arg\max_j(2c_j^\top x-\|c_j\|^2)=\arg\min_j\|x-c_j\|$. $\square$
(b) The set $\overline{\Omega_k}$ is a compact subset of $K$; by Tietze's theorem $f_k$ extends to a continuous function $\tilde f_k$ on $K$. ReLU networks are dense in $C(K)$ (Leshno–Lin–Pinkus–Schocken, ReLU is not a polynomial), so there is $E_k$ with $\sup_K\|E_k-\tilde f_k\|\le\varepsilon$. (i) If $x\in\Omega_k$, $r(x)=k$ is the only index with the maximal score, so $\Phi(x)=E_k(x)$ and $f(x)=f_k(x)=\tilde f_k(x)$: $\|f(x)-\Phi(x)\|\le\varepsilon$. (ii) Near $x$, the branches of $\Phi$ are the pieces of the $E_k$ ($k\in J(x)$) on the sets where the activations of $E_k$ are constant; they are $C^1$ (affine), and they all take the value $E_k(x)$ at $x$ because $E_k$ is continuous. By the theorem on Filippov regularization of the course, $\mathcal F[\Phi](x)=\operatorname{co}\{E_k(x):k\in J(x)\}$, and $\mathcal F[f](x)=\operatorname{co}\{f_k(x):k\in J(x)\}$ by definition. If $p=\sum\lambda_kE_k(x)$ and $q=\sum\lambda_kf_k(x)$ with the same convex weights, $\|p-q\|\le\sum\lambda_k\|E_k(x)-f_k(x)\|\le\varepsilon$: each point of one hull is within $\varepsilon$ of a point of the other, which is the Hausdorff bound. $\square$
(c) The diameter of $f(B(x_0,r)\cap K)$ decreases as $r\to0$ to $\omega$, so it is $\ge\omega$ for every $r$. Let $\theta>0$. $G$ is continuous at $x_0$: there is $r>0$ with $\|G(y)-G(z)\|<\theta$ for $y,z\in B(x_0,r)\cap K$. Choose such $y,z$ with $\|f(y)-f(z)\|\ge\omega-\theta$. Then $\omega-\theta\le\|f(y)-G(y)\|+\|G(y)-G(z)\|+\|G(z)-f(z)\|\le2\sup_K\|f-G\|+\theta$, so $\sup_K\|f-G\|\ge\omega/2-\theta$ for every $\theta>0$. $\square$
Interactive illustration. Approximate a target with two jumps: a continuous network against a router with three experts.
# Filippov network = hard router (argmax of affine scores = Voronoi cells) + one ReLU expert per cell.import numpy as npimport matplotlib.pyplot as pltrelu = lambda z: np.maximum(z, 0)centres = np.array([0.2, 0.5, 0.9]) # scores s_j(x) = 2 c_j x - c_j^2: cells [0, .35], [.35, .7], [.7, 1]branches = [lambda x: 0.5 + 0.3 * np.sin(9 * x), lambda x: -0.5 + 0.4 * np.cos(7 * x), lambda x: 0.6 - 1.2 * (x - 0.7)]route = lambda x: np.argmax(2 * np.outer(x, centres) - centres ** 2, axis=1)f = lambda x: np.choose(route(x), [b(x) for b in branches]) # discontinuous target (jumps at 0.35 and 0.7)def fit(x, y, lo, hi, n): kn = lo + (hi - lo) * (np.arange(n) + 0.5) / n A = np.column_stack([np.ones_like(x), x] + [relu(x - k) for k in kn]) c = np.linalg.lstsq(A, y, rcond=None)[0] return lambda t: np.column_stack([np.ones_like(t), t] + [relu(t - k) for k in kn]) @ cx = np.linspace(0, 1, 2001)off = (np.abs(x - 0.35) > 0.004) & (np.abs(x - 0.7) > 0.004) # away from the router boundariesbounds = [0, 0.35, 0.7, 1]jump = max(abs(branches[0](0.35) - branches[1](0.35)), abs(branches[1](0.7) - branches[2](0.7)))print(f"largest jump {jump:.3f}: every continuous network has sup error >= {jump / 2:.3f}")print(" n | continuous net, 3n units (whole interval) | Filippov net, 3 experts of n units (off the boundaries)")for n in (1, 2, 4, 8, 12): g = fit(x, f(x), 0, 1, 3 * n) E = [fit(x[(x >= bounds[j]) & (x <= bounds[j + 1])], branches[j](x[(x >= bounds[j]) & (x <= bounds[j + 1])]), bounds[j], bounds[j + 1], n) for j in range(3)] Phi = np.choose(route(x), [E[j](x) for j in range(3)]) print(f"{n:2d} | {np.max(np.abs(g(x) - f(x))):24.3f} | {np.max(np.abs(Phi - f(x))[off]):.4f}")# Filippov set at the first boundary: convex hull of the values of the active experts (here an interval)print("Filippov set of the network at x = 0.35:", sorted([float(E[0](np.array([0.35]))[0]), float(E[1](np.array([0.35]))[0])]), "; of f:", sorted([branches[0](0.35), branches[1](0.35)]))plt.plot(x, f(x), "k--"); plt.plot(x, Phi); plt.plot(x, g(x)); plt.show()
Reading. (a) says that routing alone is universal (it is a piecewise constant approximation: the price is the number of experts, of order $(1/h)^n$). (b) is the new statement of the Filippov setting: a target that jumps is approximated up to the router boundaries by experts that are ordinary smooth networks, and at the boundary the Filippov set of the network follows that of the target, which classical theorems (all of Parts 1–5, which concern continuous functions) cannot express. (c) shows that the router is not a luxury: no continuous network does better than half the jump, however many units it has. Limits. The router is taken with given cells (the interfaces of $f$ are known and are hyperplanes of a Voronoi diagram); learning the interfaces is another matter. The values of the network on the boundary are not controlled (a tie returns one branch, as Keras does), only its Filippov set; and the closeness of the derivatives, needed for gradients and relevance propagation, would require smooth activations (Hornik 1991) instead of ReLU.
Part 6 · Comparison and limits
Differences between the results
| Property | Cybenko / Hornik | Leshno–Pinkus | Barron | Depth separation | Minimal width |
|---|---|---|---|---|---|
| Type of statement | density | density, iff | rate | lower bound on size | density, bounded width |
| Activation | bounded, monotone or sigmoidal | continuous, non-polynomial | sigmoidal | ReLU (piecewise linear) | ReLU or general |
| What grows | width | width | width ($N$) | width needed by shallow nets | depth |
| Norm | uniform on a compact | uniform on compacts | $L^2(\mu)$ | $L^1$ / $L^2$ / exact | uniform or $L^p$ |
| Proof tool | Weierstrass / Hahn–Banach | Baire, derivatives, Weierstrass | Fourier, Maurey sampling | counting pieces | topology of level sets, constructions |
| Explicit size | no | no | $\sim C_f^2/\varepsilon^2$ | yes ($2^k$) | width yes, depth no |
Three results that look contradictory are not: Part 1 says one hidden layer is enough; Part 3 says it can be exponentially expensive; Part 4 says that a very narrow network is enough. They answer different questions about the same set of functions: existence of some size, size needed for a particular target, shape of the network at a given size.
Generalization: a network can fit anything
Let $x_1,\dots,x_N\in\mathbb R^d$ be distinct points and $y_1,\dots,y_N\in\mathbb R$ arbitrary. There is a network $F(x)=c+\sum_{j=1}^{N-1}\alpha_j\,\mathrm{ReLU}(w^{\top}x-\tau_j)$ with one hidden layer of $N-1$ units such that $F(x_i)=y_i$ for all $i$. With the logistic function $\sigma$, $N$ hidden units suffice for an exact fit, $F(x_i)=y_i$.
Proof
ReLU. The $w\in\mathbb R^d$ with $w^{\top}x_i=w^{\top}x_k$ for some $i\ne k$ form a finite union of hyperplanes, so there is $w$ such that the numbers $t_i=w^{\top}x_i$ are pairwise distinct; relabel so that $t_1<\dots<t_N$. Put $s_i=(y_{i+1}-y_i)/(t_{i+1}-t_i)$ for $1\le i\le N-1$, $c=y_1$, $\tau_j=t_j$, $\alpha_1=s_1$ and $\alpha_j=s_j-s_{j-1}$ for $j\ge2$. As a function of $u=w^{\top}x$, $F=y_1+\sum_j\alpha_j\max(u-t_j,0)$ equals $y_1$ for $u\le t_1$ and has slope $\alpha_1+\dots+\alpha_j=s_j$ on $[t_j,t_{j+1}]$. Hence $F(x_i)=y_1+\sum_{k<i}s_k(t_{k+1}-t_k)=y_i$. $\square$
Logistic function. With the same $w$ and $\eta=\tfrac12\min_i(t_{i+1}-t_i)$, take the $N$ units $\sigma(\lambda(w^{\top}x-t_j+\eta))$. At $x_i$ the argument is $\lambda(t_i-t_j+\eta)$, which is $\ge\lambda\eta$ if $j\le i$ and $\le-\lambda\eta$ if $j>i$. When $\lambda\to\infty$ the $N\times N$ matrix $M_\lambda=[\sigma(\lambda(t_i-t_j+\eta))]_{ij}$ converges to the lower triangular matrix of ones, whose determinant is $1$. So $\det M_\lambda\ne0$ for $\lambda$ large, and $M_\lambda\alpha=y$ has a solution: $F(x_i)=y_i$. $\square$
Interactive illustration. Fit $N$ noisy points exactly with $N-1$ ReLU units, then remove units.
# A one-hidden-layer ReLU network with N-1 units interpolates any N labels, noise included.import numpy as npimport matplotlib.pyplot as pltrelu = lambda z: np.maximum(z, 0)rng = np.random.default_rng(1)N = 24x = np.sort((np.arange(N) + 0.2 + 0.6 * rng.uniform(size=N)) / N)def interpolate(x, y): """Proof of the theorem: F(t) = y_1 + sum_j c_j relu(t - x_j), with c_j the change of slope at x_j.""" s = np.diff(y) / np.diff(x) # slopes of the piecewise-linear interpolant c = np.concatenate([[s[0]], np.diff(s)]) # c_1 = s_1, c_j = s_j - s_{j-1} return lambda t: y[0] + relu(np.asarray(t)[:, None] - x[:-1]) @ cdef lstsq_net(x, y, m): """Same class, only m units (knots at m of the data points), output weights by least squares.""" kn = x[(np.arange(m) * (N - 1)) // m] A = np.column_stack([np.ones_like(x)] + [relu(x - t) for t in kn]) c = np.linalg.lstsq(A, y, rcond=None)[0] return lambda t: np.column_stack([np.ones_like(t)] + [relu(t - k) for k in kn]) @ cfor name, f, y in [("signal + noise", lambda t: 0.8 * np.sin(2 * np.pi * t), None), ("pure noise", lambda t: 0 * t, None)]: y = 0.8 * np.sin(2 * np.pi * x) + 0.3 * rng.normal(size=N) if name != "pure noise" else 2 * rng.uniform(size=N) - 1 t = np.linspace(x[0], x[-1], 400) F = interpolate(x, y) print(f"{name}: max |F(x_i) - y_i| = {np.max(np.abs(F(x) - y)):.1e} (N-1 = {N-1} units)") for m in (3, 6, 12, N - 1): G = lstsq_net(x, y, m) print(f" m = {m:2d}: train {np.sqrt(np.mean((G(x) - y) ** 2)):.3f} error against the truth {np.sqrt(np.mean((G(t) - f(t)) ** 2)):.3f}") plt.figure(); plt.plot(t, f(t), "k--"); plt.plot(t, F(t)); plt.plot(x, y, "ro"); plt.title(name)plt.show()
Consequences for the point on generalization. (i) The class fits pure noise: take for $y_i$ independent random signs; the network above has training error $0$ whatever the labels, so a network with $N-1$ units shatters any $N$ points, which means maximal empirical Rademacher complexity. No guarantee on the generalization error can use only the fact that the class is universal. (ii) Two networks with the same data and zero training error can differ arbitrarily between the points (add to $F$ any network vanishing at the $x_i$). What generalizes is a property of the selected function (small norm, few units, flat minimum), not of the class: this is the role of regularization, early stopping and the implicit bias of gradient descent.
Precision and stability: the weights must be large
Let $\sigma\in C^1(\mathbb R)$ with $|\sigma'|\le L$ ($L=\tfrac14$ for the logistic function, $L=1$ for $\tanh$ and for ReLU), and $F(x)=c+\sum_{i=1}^{N}\alpha_i\,\sigma(\omega_i^{\top}x+b_i)$ with $\sum_i|\alpha_i|\le A$ and $\|\omega_i\|\le W$. Then:
- $F$ is Lipschitz with constant $LAW$: $|F(x)-F(y)|\le LAW\,\|x-y\|$.
- If $f$ satisfies $|f(x)-f(y)|\ge1$ for two points at distance $\delta$, and $\sup|F-f|\le\varepsilon$, then $\;LAW\ge\dfrac{1-2\varepsilon}{\delta}$.
- For every $A$ and $W$, the networks with $\sum|\alpha_i|\le A$ and $\|\omega_i\|\le W$ (any $N$) are not dense in $C([a,b])$: their uniform closure consists of $LAW$-Lipschitz functions.
Proof
(1) By the mean value theorem $|\sigma(\omega_i^{\top}x+b_i)-\sigma(\omega_i^{\top}y+b_i)|\le L\,|\omega_i^{\top}(x-y)|\le LW\|x-y\|$; multiplying by $|\alpha_i|$ and summing gives $|F(x)-F(y)|\le LW\big(\sum|\alpha_i|\big)\|x-y\|\le LAW\|x-y\|$. (2) $1\le|f(x)-f(y)|\le|f(x)-F(x)|+|F(x)-F(y)|+|F(y)-f(y)|\le2\varepsilon+LAW\delta$. (3) A uniform limit of $K$-Lipschitz functions is $K$-Lipschitz (pass to the limit in the inequality at fixed $x,y$), whereas $C([a,b])$ contains functions that are not Lipschitz, or have a larger constant. $\square$
Interactive illustration. Make a sigmoidal network jump from 0 to 1 over a shorter and shorter interval.
# Cost of sharpness: a network with sum|alpha_i| <= A_tot and |w_i| <= W is (L*W*A_tot)-Lipschitz.import numpy as npimport matplotlib.pyplot as pltsigmoid = lambda z: 1 / (1 + np.exp(-z))L = 0.25 # sup |sigmoid'|def best_error(delta, W, N): """Uniform error of F = (1/N) sum_j sigmoid(W (x - c_j)) (so sum|alpha_j| = 1) against the ramp of width delta.""" x = np.sort(np.concatenate([np.linspace(0, 1, 401), 0.5 + 2 * delta * np.linspace(-1, 1, 201)])) y = np.clip((x - 0.5) / delta + 0.5, 0, 1) c = 0.5 + delta * (np.linspace(-0.5, 0.5, N) if N > 1 else np.zeros(1)) F = np.mean([sigmoid(W * (x - cj)) for cj in c], axis=0) return np.max(np.abs(F - y)), 1.0delta, N = 0.01, 3print("W error L*W*sum|a| guaranteed error (1 - L W sum|a| delta)/2")Ws = np.logspace(0, 3, 31)res = []for W in Ws: e, s = best_error(delta, W, N) lb = max(0, (1 - L * W * s * delta) / 2) assert e >= lb - 1e-9 # the theorem res.append((e, lb)) if abs(np.log10(W) - round(np.log10(W))) < 1e-9 or W in Ws[::5]: print(f"{W:6.0f} {e:7.3f} {L*W*s:11.1f} {lb:10.3f}")res = np.array(res)plt.loglog(Ws, res[:, 0], label="uniform error"); plt.loglog(Ws, np.maximum(res[:, 1], 1e-3), "--", label="lower bound")plt.xlabel("W"); plt.legend(); plt.show()
Consequences for the point on precision. In Step 1 of Cybenko's proof, approximating a step of width $\delta$ with error $\varepsilon<\tfrac12$ requires $LAW\ge(1-2\varepsilon)/\delta$: the weights must grow like $1/\delta$ when the accuracy increases, and this is not an artefact of the construction. Density is therefore a statement about unbounded weights; a network trained with weight decay, or stored with a limited precision, lives in a Lipschitz ball and can follow a target only up to the sharpness that this ball allows. Conversely, $LAW$ bounds the sensitivity of the output to an input perturbation, which is a (crude) robustness certificate.
Sizes in practice: density has no rate
Let $\Sigma_N$ be the set of functions $F(x)=c+\sum_{j=1}^{N}\alpha_j\,\mathrm{ReLU}(w_jx-\tau_j)$ on $[0,1]$ ($c,\alpha_j,w_j,\tau_j$ real). Then:
- Zigzag. For every $N\ge0$ and $a>0$, the piecewise linear function $f_{N,a}$ with $f_{N,a}(i/(N+2))=(-1)^ia$ for $i=0,\dots,N+2$ satisfies $\|f_{N,a}\|_\infty=a$, $\mathrm{Lip}(f_{N,a})=2a(N+2)$ and $\operatorname{dist}_\infty(f_{N,a},\Sigma_N)\ge a$.
- No uniform rate. For every $N$, $\sup_{\|f\|_\infty\le1}\operatorname{dist}(f,\Sigma_N)=1$. There is no sequence $\varepsilon_N\to0$ such that $\operatorname{dist}(f,\Sigma_N)\le\varepsilon_N\|f\|_\infty$ for all $f\in C([0,1])$.
- Arbitrarily slow convergence for one function. For every non-increasing sequence $\varepsilon_N\to0$ there is $f\in C([0,1])$ with $\operatorname{dist}(f,\Sigma_N)\ge\varepsilon_N$ for all $N$, although $\operatorname{dist}(f,\Sigma_N)\to0$ (density).
- Lipschitz functions. Among functions with $\mathrm{Lip}(f)\le K$, $\sup\operatorname{dist}(f,\Sigma_N)\ge K/(2(N+2))$: the rate $1/N$ cannot be beaten, even in dimension $1$.
Proof
Lemma (pieces and zeros). A function $F\in\Sigma_N$ is piecewise linear with at most $N+1$ pieces (each unit has one kink, at $\tau_j/w_j$). Let $x_0<\dots<x_M$ be points with $F(x_i)F(x_{i+1})<0$ for $0\le i<M$. Then $M\le N+1$. Indeed, by the intermediate value theorem $F$ has a zero $z_i\in(x_i,x_{i+1})$ for each $i$. Two of them, $z_i<z_j$ ($i<j$), cannot lie in the same linear piece: this piece would contain $x_{i+1}\in(z_i,z_j)$, and an affine function with two zeros vanishes identically, so $F(x_{i+1})=0$, which is excluded. So the $M$ zeros lie in $M$ distinct pieces, and $M\le N+1$. $\square$
Interactive illustration. For every $N$, a zigzag that $N$ ReLU units cannot approximate better than its own amplitude.
# No uniform rate: for every N, a zigzag with N+2 alternations of amplitude a that N ReLU units cannot approximate better than a.import numpy as npimport matplotlib.pyplot as pltrelu = lambda z: np.maximum(z, 0)x = np.linspace(0, 1, 801)def zigzag(N, a): knots = np.linspace(0, 1, N + 3) # N + 3 points = N + 2 intervals return np.interp(x, knots, a * (-1.0) ** np.arange(N + 3))def best_fit_error(f, N, rng, tries=60): """Smallest uniform error found over `tries` choices of the N knots (output weights by least squares).""" best = np.inf for t in range(tries): kn = np.sort(rng.uniform(size=N)) if t else np.linspace(0, 1, N + 3)[1:N + 1] A = np.column_stack([np.ones_like(x), x] + [relu(x - k) for k in kn]) c = np.linalg.lstsq(A, f, rcond=None)[0] best = min(best, np.max(np.abs(A @ c - f))) return bestrng = np.random.default_rng(0)print(" N | a (unit ball) | best error found | K/(2(N+2)) with K=20 | best error found")res = []for N in range(1, 21): a1, a2 = 1.0, min(1.0, 20 / (2 * (N + 2))) e1, e2 = best_fit_error(zigzag(N, a1), N, rng), best_fit_error(zigzag(N, a2), N, rng) assert e1 >= a1 - 1e-9 and e2 >= a2 - 1e-9 # the theorem: no network with N units does better than a res.append((N, e1, a2, e2)) if N in (1, 2, 4, 8, 12, 16, 20): print(f"{N:2d} | {a1:13.2f} | {e1:16.3f} | {a2:21.3f} | {e2:.3f}")res = np.array(res)plt.semilogy(res[:, 0], res[:, 1], label="unit ball: error"); plt.semilogy(res[:, 0], res[:, 3], label="K = 20: error")plt.semilogy(res[:, 0], res[:, 2], "--", label="bound K/(2(N+2))"); plt.xlabel("N"); plt.legend(); plt.show()
Reading. Density says that for each $f$ the error tends to $0$; it does not say how fast, and the theorem shows that no speed holds for all functions: one hidden layer needs more and more units for functions that oscillate more and more, and the oscillation of the worst function can be as slow or as fast as one wishes. Rates therefore need a class of targets (Lipschitz, Barron, Sobolev…) and the rate depends on the class: this is the content of Barron's theorem (Part 2) and of the lower bounds of Maiorov and Pinkus. For another activation the same statements hold with other proofs (zero counting for sigmoids, or the general results on continuous parametrizations by DeVore, Howard and Micchelli); the proof above is given for ReLU because the count of pieces is elementary.
What none of these theorems says
- Optimization. All results are about the set of functions a network can represent. Training minimizes a non-convex loss by stochastic gradient descent; nothing above says that it finds the approximating weights (see the SGD page).
- Generalization. Approximating a known function $f$ on a compact set is not learning from a finite sample: a network that interpolates $N$ noisy points is also a universal approximator in the sense of Part 1.
- Sizes in practice. Density has no rate; Barron’s rate hides $C_f$ and applies to a restricted class; depth separations use special targets; minimal-width constructions are impractically deep.
- Precision and stability. The weights in the constructions may be huge (sharpened sigmoids, Step 1 of Cybenko), which is incompatible with finite precision and with the small weights found by training.
- Which activation, which architecture. Universality holds for almost every non-polynomial activation: it cannot explain why ReLU or GELU work better than sigmoid. Likewise it does not distinguish between an MLP, a CNN and a Transformer.
The theorems are best read as sanity checks (the model class is not too small, and polynomial activations are excluded for a reason) and as sources of mechanisms: sharpened sigmoids make steps, ReLU units make pieces, depth composes oscillations.
Which activation? Trainability, not approximation
Let $F(x)=W_{L+1}\,\sigma(W_L\,\sigma(\cdots\sigma(W_1x+b_1)\cdots)+b_L)+b_{L+1}$ with $\sigma$ differentiable applied coordinatewise, and $\gamma=\sup|\sigma'|$. Then:
- Bound. For all $x$, $\ \|DF(x)\|_2\le\gamma^{L}\prod_{l=1}^{L+1}\|W_l\|_2$. The same bound holds for $\partial F/\partial b_l$ and for $\partial F/\partial W_l$ divided by $\|h_{l-1}\|$, with the product restricted to the layers above $l$.
- Logistic function. $\gamma=\tfrac14$: if $\|W_l\|_2\le w$ for all $l$, then $\|DF\|\le w\,(w/4)^{L}$, which tends to $0$ exponentially in $L$ when $w<4$.
- No obstruction for ReLU. $\gamma=1$, and the bound is attained: with $W_1=\dots=W_{L+1}=\mathrm{Id}$, $b=0$ and $x$ with positive coordinates, $F(x)=x$ and $DF(x)=\mathrm{Id}$ for every $L$. The same holds for GELU, for which $\gamma=\sup\mathrm{GELU}'\approx1.129>1$ does not force any decay.
- Signal propagation. If $h_0=x$, $h_l=\mathrm{ReLU}(W_lh_{l-1})$ with the entries of $W_l\in\mathbb R^{n\times n}$ independent $N(0,2/n)$, then $\mathbb E\|h_l\|^2=\|x\|^2$ for all $l$.
Proof
(1) The chain rule gives $DF(x)=W_{L+1}D_LW_L\cdots D_1W_1$ with $D_l=\mathrm{diag}(\sigma'(z_l))$, $\|D_l\|_2\le\gamma$, and $\|AB\|_2\le\|A\|_2\|B\|_2$. For $\partial F/\partial b_l$ drop the factors below $l$; for $\partial F/\partial W_l$, $\partial h_l/\partial W_l$ is linear in $h_{l-1}$ with norm $\le\gamma\|h_{l-1}\|$. (2) $\sigma'=\sigma(1-\sigma)\le\tfrac14$. (3) $\mathrm{ReLU}'\in\{0,1\}$ and equals $1$ at positive arguments, so $D_l=\mathrm{Id}$ and $DF=\mathrm{Id}$. For GELU, $\mathrm{GELU}(z)=z\Phi(z)$ and $\mathrm{GELU}'(z)=\Phi(z)+z\varphi(z)$ has maximum $\approx1.129$ (at $z\approx1.4$), so (1) gives no decay. (4) Condition on $h=h_{l-1}$. Each $z_i=(W_lh)_i$ is $N(0,2\|h\|^2/n)$, symmetric, hence $\mathbb E\,\mathrm{ReLU}(z_i)^2=\tfrac12\mathbb Ez_i^2=\|h\|^2/n$; summing over the $n$ coordinates, $\mathbb E[\|h_l\|^2\mid h_{l-1}]=\|h_{l-1}\|^2$, and the claim follows by induction. $\square$
Interactive illustration. Random deep networks with four activations: how large is the derivative after $l$ layers?
# Gradient attenuation: ||DF|| <= prod ||W_l|| * (sup |sigma'|)^L, and signal propagation of ReLU at He initialization.import numpy as npfrom math import erf, sqrt, pi, expn, depth, trials = 48, 30, 12sig = lambda z: 1 / (1 + np.exp(-z))phi = np.vectorize(lambda z: 0.5 * (1 + erf(z / sqrt(2))))acts = { "logistic": (sig, lambda z: sig(z) * (1 - sig(z)), 0.25), "tanh": (np.tanh, lambda z: 1 - np.tanh(z) ** 2, 1.0), "ReLU": (lambda z: np.maximum(z, 0), lambda z: (z > 0) * 1.0, 1.0), "GELU": (lambda z: z * phi(z), lambda z: phi(z) + z * np.exp(-z * z / 2) / sqrt(2 * pi), 1.129),}for g in (np.sqrt(2), 3.0): print(f"\nweights N(0, g^2/n) with g^2 = {g**2:.1f}") print("activation | log10 |J v|/|v| after 30 layers | log10 of the mean of |h|^2/|x|^2 | log10 of the bound prod(gamma ||W||)") for name, (f, df, gam) in acts.items(): J, H, B = [], [], [] for t in range(trials): r = np.random.default_rng(t) x = r.normal(size=n); v = r.normal(size=n); v /= np.linalg.norm(v); h = x.copy(); b = 0.0 for l in range(depth): W = r.normal(size=(n, n)) * g / np.sqrt(n) z = W @ h; v = df(z) * (W @ v); h = f(z); b += np.log10(gam * np.linalg.norm(W, 2)) assert np.linalg.norm(v) <= 10 ** b * (1 + 1e-9) or l < 0 # the theorem: |Jv| <= prod gamma ||W|| J.append(np.log10(np.linalg.norm(v))); H.append(h @ h / (x @ x)); B.append(b) print(f"{name:10s} | {np.mean(J):32.1f} | {np.log10(np.mean(H)):18.2f} | {np.mean(B):.1f}")
Reading. The approximation theorems cannot separate activations: the logistic function $\sigma$ is approximated within $\varepsilon$ on $[-R,R]$ by a piecewise linear function with $m\approx2R/h$ pieces, $h^2\sup|\sigma''|/8\le\varepsilon$, so with $R=\ln(1/\varepsilon)$ a sigmoid unit costs $O(\ln(1/\varepsilon)/\sqrt\varepsilon)$ ReLU units, and conversely a ReLU is a limit of sharpened sigmoids, at the price in the weights given by the cost of sharpness; both classes approximate the same functions up to such factors. What the theorem above separates is trainability: with a logistic function the derivative of a deep network is damped geometrically unless the weights are large (and then the units saturate, which the bound does not describe but the animation shows), whereas ReLU and GELU do not impose this loss, and the He initialization of ReLU preserves the size of the signal. This is a statement on upper bounds for sigmoids and on the existence of good weights for ReLU; it says nothing about generalization, and it does not rank ReLU against GELU. Limits. Normalization layers and residual connections remove most of this obstruction for all activations, which is why modern networks use them.
Which architecture? Locality and symmetry
Inputs are in $[-1,1]^d$ and $f(x)=x_1x_d$ (so $\|f\|_\infty=1$).
- Locality of convolutions. Let $F$ be computed by $\ell$ zero-padded one-dimensional convolution layers with filters of odd length $s=2\rho_0+1$ and arbitrary pointwise activations, followed by a readout that is either one output position or a sum (pooling) over positions. Then $F(x)=\sum_ig_i(x_{i-\rho},\dots,x_{i+\rho})$ for some functions $g_i$ with $\rho=\ell\rho_0$. If $2\rho<d-1$, that is $\ell<(d-1)/(s-1)$, then $\sup_{[-1,1]^d}|f-F|\ge1$, whatever the widths, the activations and the weights: no better than $F=0$.
- Dense networks. For every $N\ge1$ there is a one-hidden-layer ReLU network with $2N$ units, whatever $d$, with $\sup|f-F|\le2/N^2$.
- Equivariance of attention. A self-attention layer without positional encoding satisfies $F(XP)=F(X)P$ for every permutation matrix $P$ of the tokens (columns of $X$). Let $T(X)$ be the sequence whose every token is the first token of $X$. Then every such $F$ satisfies $\sup\|T(X)-F(X)\|\ge\tfrac12\|a-b\|$ for tokens $a\ne b$; with a positional encoding the obstruction disappears.
Proof
(a) The output at position $i$ after one layer depends on the inputs at distance $\le\rho_0$ (zero padding only removes inputs), so after $\ell$ layers on those at distance $\le\ell\rho_0=\rho$; pointwise activations do not change this. Since $2\rho<d-1$, no window contains both indices $1$ and $d$. Let $x^{ab}$ be the point with $x_1=a$, $x_d=b$, the other coordinates $0$, $a,b\in\{\pm1\}$. Each $g_i(x^{ab})$ depends on $a$ only, on $b$ only or on neither, so $\sum_ig_i(x^{ab})=U(a)+V(b)$ and $\sum_{a,b}ab\,F(x^{ab})=\sum_{a,b}ab\,(U(a)+V(b))=0$. But $\sum_{a,b}ab\,f(x^{ab})=\sum_{a,b}(ab)^2=4$. Hence $4=\sum_{a,b}ab\,(f-F)(x^{ab})\le4\sup|f-F|$. $\square$
(b) Let $P$ be the piecewise linear interpolant of $z^2$ on $[-2,2]$ with $N$ equal intervals of length $h=4/N$; it is a ReLU network with $N$ units (interpolation theorem) and $0\le P(z)-z^2\le h^2/4$. Since $x_1x_d=\tfrac14((x_1+x_d)^2-(x_1-x_d)^2)$ with arguments in $[-2,2]$, $F=\tfrac14(P(x_1+x_d)-P(x_1-x_d))$ has $2N$ units and $|F-f|\le\tfrac14\cdot\tfrac{h^2}4\cdot2=h^2/8=2/N^2$. $\square$
(c) Self-attention computes $\mathrm{softmax}(\ldots)$ weights from $x_i^\top Qx_j$ and a value for each token; permuting the tokens permutes the rows and columns of the score matrix in the same way, hence permutes the outputs. Position-wise layers commute with permutations, so $F(XP)=F(X)P$ for the whole network. Take $X=(a,b)$ and $X'=(b,a)=XP$ with $P$ the transposition. $T(X)=(a,a)$ and $T(X')=(b,b)$, while $F(X')=F(X)P$ is the transposed of $F(X)=(u,v)$, that is $(v,u)$. Then $\|T(X)-F(X)\|\ge\|a-u\|$ and $\|T(X')-F(X')\|\ge\|b-u\|$ (comparing the first tokens), and $\max(\|a-u\|,\|b-u\|)\ge\tfrac12\|a-b\|$ by the triangle inequality. $\square$
Interactive illustration. The product of the first and the last coordinate: a dense network, and sums of local functions.
# x_1 * x_d: impossible for a sum of local functions with a window < d, easy for a dense ReLU network.import numpy as npimport matplotlib.pyplot as pltd, M = 12, 700rng = np.random.default_rng(0)X = rng.uniform(-1, 1, size=(M, d)); y = X[:, 0] * X[:, -1]def local_quadratic_error(w): """Best sum of local quadratic functions of a window of w consecutive coordinates (least squares).""" pairs = [(a, b) for a in range(d) for b in range(a, d) if b - a < w] A = np.column_stack([np.ones(M), X] + [X[:, a] * X[:, b] for a, b in pairs]) c = np.linalg.lstsq(A, y, rcond=None)[0] return np.linalg.norm(A @ c - y) / np.linalg.norm(y)def square_interpolant(N): """Piecewise linear interpolant of z^2 on [-2, 2] with N intervals: N ReLU units (interpolation theorem).""" knots = np.linspace(-2, 2, N + 1) return lambda z: np.interp(z, knots, knots ** 2)print("window w | relative error of a sum of local quadratic functions")for w in (1, 3, 6, 11, 12): print(f"{w:8d} | {local_quadratic_error(w):.3f}")print("\nN | 2N units | relative error of (P(x1+xd) - P(x1-xd))/4 | bound 2/N^2 / std(1/3)")for N in (1, 2, 4, 8, 16): P = square_interpolant(N); F = (P(X[:, 0] + X[:, -1]) - P(X[:, 0] - X[:, -1])) / 4 err = np.max(np.abs(F - y)); assert err <= 2 / N ** 2 + 1e-12 print(f"{N:2d} | {2*N:8d} | {np.linalg.norm(F - y) / np.linalg.norm(y):.4f} (sup {err:.4f}) | {6 / N**2:.3f}")print("\nlayers of filters of length s needed to see both ends: ceil((d-1)/(s-1)) =", [int(np.ceil((d - 1) / (s - 1))) for s in (3, 5, 7)], "for s = 3, 5, 7")
Reading. All architectures are universal in the sense of Parts 1 to 5, and (a) and (b) show that they are nevertheless not equivalent at fixed size: a dense network connects all the inputs in one layer, a convolutional stack connects only inputs at distance $\le\ell\rho_0$ and needs depth growing like $d/s$ to represent an interaction between the two ends, and a Transformer without positional encoding is blind to the order (c). Each limitation is also an inductive bias: translation invariance and locality are what makes convolutions cheap on images, and permutation symmetry is what makes attention suitable for sets. Limits. The statements are about what an architecture can represent, with a specific target; they do not say which architecture generalizes better on a given task, and a deep convolutional stack, a Transformer with positional encoding or an MLP can all compute $x_1x_d$ once they are large enough.
References and related learning
The papers behind the theorems
- G. Cybenko, Approximation by superpositions of a sigmoidal function, Mathematics of Control, Signals and Systems 2, 303–314, 1989. doi:10.1007/BF02551274. Cybenko’s theorem and the proof by discriminatory functions (Part 1).
- K. Hornik, M. Stinchcombe, H. White, Multilayer feedforward networks are universal approximators, Neural Networks 2, 359–366, 1989. doi:10.1016/0893-6080(89)90020-8. Density for monotone bounded activations, in the uniform and $L^p$ senses.
- K.-I. Funahashi, On the approximate realization of continuous mappings by neural networks, Neural Networks 2, 183–192, 1989. doi:10.1016/0893-6080(89)90003-8. Independent proof of density for monotone sigmoids.
- K. Hornik, Approximation capabilities of multilayer feedforward networks, Neural Networks 4, 251–257, 1991. doi:10.1016/0893-6080(91)90009-T. Density holds for any bounded non-constant continuous activation: it is the architecture, not the specific sigmoid, that gives universality.
- M. Leshno, V. Ya. Lin, A. Pinkus, S. Schocken, Multilayer feedforward networks with a nonpolynomial activation function can approximate any function, Neural Networks 6, 861–867, 1993. doi:10.1016/S0893-6080(05)80131-5. The condition “not a polynomial” is necessary and sufficient.
- A. Pinkus, Approximation theory of the MLP model in neural networks, Acta Numerica 8, 143–195, 1999. doi:10.1017/S0962492900002919. Survey of density, degree of approximation and lower bounds for one hidden layer.
- A. R. Barron, Universal approximation bounds for superpositions of a sigmoidal function, IEEE Transactions on Information Theory 39, 930–945, 1993. doi:10.1109/18.256500. The $N^{-1/2}$ rate and the comparison with linear methods (Part 2).
- V. Maiorov, A. Pinkus, Lower bounds for approximation by MLP neural networks, Neurocomputing 25, 81–91, 1999. doi:10.1016/S0925-2312(98)00111-8. Limits of one-hidden-layer approximation of smooth classes.
- M. Telgarsky, Benefits of depth in neural networks, COLT 2016, arXiv:1602.04485. The sawtooth and the exponential separation (Part 3).
- R. Eldan, O. Shamir, The power of depth for feedforward neural networks, COLT 2016, arXiv:1512.03965. Radial function separating two and three layers.
- I. Safran, R. Eldan, O. Shamir, Depth separations in neural networks: what is actually being separated?, Constructive Approximation 55, 2021. doi:10.1007/s00365-021-09532-7. Separations depend on the input distribution.
- Z. Lu, H. Pu, F. Wang, Z. Hu, L. Wang, The expressive power of neural networks: a view from the width, NeurIPS 2017, arXiv:1709.02540. Width $n+4$ for ReLU in $L^1$ (Part 4).
- B. Hanin, M. Sellke, Approximating continuous functions by ReLU nets of minimal width, 2017, arXiv:1710.11278. Minimal width $n+1$ for uniform approximation.
- P. Kidger, T. Lyons, Universal approximation with deep narrow networks, COLT 2020, arXiv:1905.08539. Width $n+m+2$ for general activations.
- S. Park, C. Yun, J. Lee, J. Shin, Minimum width for universal approximation, ICLR 2021, arXiv:2006.08859. The exact width $\max(n+1,m)$ in $L^p$ for ReLU.
- T. Chen, H. Chen, Universal approximation to nonlinear operators by neural networks with arbitrary activation functions and its application to dynamical systems, IEEE Transactions on Neural Networks 6, 911–917, 1995. doi:10.1109/72.392253. Operators (Part 5).
- L. Lu, P. Jin, G. Pang, Z. Zhang, G. E. Karniadakis, Learning nonlinear operators via DeepONet based on the universal approximation theorem of operators, Nature Machine Intelligence 3, 218–229, 2021. doi:10.1038/s42256-021-00302-5. Branch/trunk architecture from Chen–Chen.
- D.-X. Zhou, Universality of deep convolutional neural networks, Applied and Computational Harmonic Analysis 48, 787–794, 2020. doi:10.1016/j.acha.2019.06.004. Universality of deep CNNs.
- C. Yun, S. Bhojanapalli, A. S. Rawat, S. Reddi, S. Kumar, Are Transformers universal approximators of sequence-to-sequence functions?, ICLR 2020, arXiv:1912.10077. Universality of Transformers.
- On this site: Neural networks with Keras (building and training the networks), Stochastic gradient descent (why training is a separate question).