Level 3 In-Depth AI · Deep Learning
Why Neural Networks Work
A network with one hidden layer can approximate any reasonable function if it is wide enough, and deep networks can do the same far more cheaply. This chapter shows why with pictures, explains what networks learn inside, and is honest about what the theory doesn't promise.
- Level
- ●●●●● Intermediate
- Reading
- 14 min
- To learn it well
- 45 minutes to read, an hour to practise
- Builds on
- 15 concepts →
- Quiz
- 4 questions ↓
Read first
Activation FunctionsThis leads to
—The full path from zero — 15 concepts before this one
- What Is AI?
- Vectors
- Derivatives and Slopes
- Probability Basics
- How Machines Learn
- Partial Derivatives and Gradients
- Matrices and Matrix Multiplication
- Supervised, Unsupervised and Reinforcement Learning
- Gradient Descent
- Supervised Learning
- Linear Regression
- The Perceptron
- Logistic Regression
- Neural Networks
- Activation Functions
- Why Neural Networks Work
Read them roughly in this order. See it on the concept map →
Why it matters
A neural network is just layers of weighted sums with simple bends between them. Yet the same recipe learns to recognise faces, transcribe speech, translate languages and write code. Why should such a plain construction be able to do so many different things?
Part of the answer is a mathematical guarantee called the universal approximation theorem: a network with a single hidden layer can get as close as you like to any continuous function, provided it has enough neurons. So there is no task that is out of reach in principle, as long as the task can be written as a smooth enough mapping from inputs to outputs.
That guarantee is often over-sold. It says nothing about how many neurons you need, whether training will find the right weights, or whether the result will work on new data. This chapter shows the theorem visually, explains why deep networks beat wide ones in practice, describes what networks actually learn inside, and lists the honest limits. It is the background you need for judging claims about what neural networks can and can't do.
The intuition
Imagine trying to trace a curve using only straight sticks. With two sticks your copy is crude. With ten it looks close. With a hundred you can hardly tell the difference. Any smooth curve can be approximated this way, with enough sticks.
A layer of ReLU neurons is a box of sticks. Each ReLU neuron, , is flat up to some point and then rises in a straight line: a ramp with a hinge. Add several ramps with different hinge points and different steepness, and you get a bent line that changes direction at each hinge. Choose the hinges and slopes well and the bent line follows whatever curve you want.
In higher dimensions the same thing happens with flat pieces instead of sticks. Each ReLU neuron splits the input space with a flat cut and is "on" on one side of it. Many cuts chop the space into many regions, and the network is a different flat function in each region. With enough regions it can approximate any continuous surface. Other activation functions, such as sigmoid, work similarly with smooth steps instead of ramps.
Key idea A wide enough one-hidden-layer network can approximate any continuous function, by adding up many simple bends. Depth makes this exponentially cheaper for many functions. But the theorem promises only that good weights exist, not that training finds them or that they generalise.
How it works
Building sin(x) by hand
Let's make the picture exact. We want a network with one input , one hidden layer of ReLUs and one output that approximates for from 0 to .
The plan is to join up points on the curve with straight segments. Pick evenly spaced knots and draw straight lines between the points . The result is a piecewise linear function: made of straight pieces joined at corners. A one-hidden-layer ReLU network can represent it exactly, with one hidden neuron per piece:
Hidden neuron has input weight 1 and bias , so it switches on at knot . Its output weight is the change in slope at that knot: the slope of the new segment minus the slope of the previous one. Once a ramp switches on it stays on, so each new neuron only has to correct the slope.
Work it through with . The knots are and the sine values there are . Each segment is wide, so the slopes of the four segments are:
- : rises by 1, slope
- : falls by 1, slope
- : falls by 1, slope
- : rises by 1, slope
The changes in slope give the output weights: , , (the slope doesn't change at ), and . So the network is
Check one point. At only the first ramp is on, so . The true value is , so the error is 0.207, about the worst anywhere on this copy. Now check : the first two ramps are on, giving . Exactly .
Add more knots and the error shrinks fast. Measured over 10,001 points:
| Hidden neurons | Max error |
|---|---|
| 2 | 1.000 |
| 4 | 0.211 |
| 8 | 0.070 |
| 16 | 0.019 |
| 32 | 0.005 |
| 64 | 0.001 |
(With 2 neurons all three knots land where is 0, so the copy is a flat line and misses the peaks entirely.) Each doubling of neurons cuts the error by about 4. You can push it below any tolerance you name. That is universal approximation in one dimension.
The theorem
The same argument extends to many inputs and to other activation functions, though the proofs are harder. Stated loosely:
For any continuous function on a bounded region, and any tolerance , there is a network with one hidden layer whose output is within of everywhere in that region.
The symbol ("epsilon") is the allowed error. George Cybenko proved this for sigmoid networks in 1989, and Kurt Hornik, Maxwell Stinchcombe and Halbert White proved a general version the same year. Later work showed the activation function only needs to be non-polynomial. ReLU, sigmoid, tanh, GELU all qualify. A polynomial activation does not, because a sum of polynomials of fixed degree is still a polynomial of that degree.
Depth versus width
If one hidden layer is enough, why do practical networks have dozens or hundreds of layers? Because "enough" can be astronomically many neurons, and depth can be exponentially cheaper.
Here is a clean example. The tent function uses two ReLUs. On the interval 0 to 1 it rises from 0 to 1 and falls back to 0: two straight pieces. Now feed its output into another copy of itself, . Each half of the tent gets stretched over the whole interval and folded again, giving four pieces. Three layers give eight.
With layers and only neurons, the network computes a zig-zag with pieces. A single hidden layer can add at most one corner per neuron, so it needs roughly neurons to draw the same zig-zag. At that's 40 neurons deep versus about a million wide. Matus Telgarsky proved in 2016 that this gap is real: some functions computed by deep networks need exponentially many neurons to approximate with shallow ones. Results of this kind are called depth separation.
The intuition is reuse. A deep network computes intermediate results once and builds on them many times, the way a program calls a subroutine. A wide, shallow network has to compute every combination from scratch.
Representation learning
The theorem treats a network as a curve-fitting machine. The more useful way to see a deep network is as a stack of representations. Each layer turns its input into a new list of numbers, a new description of the data, and passes it on. The Neural Networks chapter showed a hidden layer moving the XOR points until a straight line could separate them. Deep networks do this over and over.
Training discovers these descriptions on its own. This is representation learning, and it is the real reason deep learning works so well:
- In image networks, early layers respond to edges and colour blobs, middle layers to textures and simple parts, and later layers to whole objects. Researchers can see this by finding the images that most excite each neuron (see Interpretability and Explainability).
- In language models, the internal vectors come to encode word meaning, grammar and facts. Similar words end up near each other, which is the idea behind Word Embeddings.
- A representation learned for one task is often useful for others. That's why Transfer Learning works: you can take a network trained on millions of images and reuse its layers for X-ray scans.
Architecture as a hint
Universal approximation says a plain MLP could do anything. In practice, the architecture builds in assumptions about the data that make learning far easier. These assumptions are called inductive biases.
- A convolutional network assumes that a pattern means the same thing wherever it appears in an image, so it reuses the same small filter at every position.
- A recurrent network assumes the same rule applies at every step of a sequence.
- A The Transformer assumes that any position may need information from any other, and lets each position decide where to look.
A good inductive bias cuts the number of parameters and examples needed by orders of magnitude.
The honest limits
The universal approximation theorem is true and important, but it is easy to read too much into it.
- It doesn't say how big. The number of neurons needed can grow exponentially with the number of inputs. For a function of 1,000 inputs, "some network exists" may mean one larger than the universe.
- It doesn't say training will find it. The theorem says good weights exist. Gradient Descent might not reach them. In the code below, a trained 8-neuron network ends with a worse error than our hand-built 8-neuron one.
- It doesn't say it will generalise. Fitting a function perfectly on the training points says nothing about points in between, or outside the range. A network that matches on 0 to can be wildly wrong at . See Overfitting and the Bias–Variance Tradeoff.
- It only covers continuous functions on a bounded region. Not arbitrary programs, and not extrapolation.
Deep learning works much better in practice than the classical theory can fully explain. Large networks have enough parameters to memorise their training data, yet they usually generalise well. Why gradient descent finds solutions that generalise is an active research question, discussed further in Dropout and Regularizing Neural Networks and Scaling Laws.
In code
First, the hand-built network. No training: the weights are computed directly from the knots, exactly as above.
import numpy as np
f = np.sin # the function to approximate
relu = lambda z: np.maximum(0, z)
def relu_net(n):
"""One hidden layer of n ReLUs that joins up n+1 points on sin(x)."""
knots = np.linspace(0, 2 * np.pi, n + 1)
slopes = np.diff(f(knots)) / np.diff(knots)
w_hidden = np.ones(n) # every hidden neuron sees x
b_hidden = -knots[:-1] # neuron k switches on at knot k
w_out = np.diff(slopes, prepend=0) # change of slope at each knot
b_out = f(knots[0])
return lambda x: relu(np.outer(x, w_hidden) + b_hidden) @ w_out + b_out
x = np.linspace(0, 2 * np.pi, 10001)
for n in [2, 4, 8, 16, 32, 64]:
err = np.max(np.abs(relu_net(n)(x) - f(x)))
print(f"{n:3d} hidden neurons: max error {err:.4f}")
# 2 hidden neurons: max error 1.0000
# 4 hidden neurons: max error 0.2105
# 8 hidden neurons: max error 0.0704
# 16 hidden neurons: max error 0.0188
# 32 hidden neurons: max error 0.0048
# 64 hidden neurons: max error 0.0012
Now let gradient descent find the weights instead, in PyTorch:
import math
import torch
from torch import nn
torch.manual_seed(0)
x = torch.linspace(0, 2 * math.pi, 200).unsqueeze(1) # shape (200, 1)
y = torch.sin(x)
for width in [2, 8, 32]:
net = nn.Sequential(nn.Linear(1, width), nn.ReLU(), nn.Linear(width, 1))
opt = torch.optim.Adam(net.parameters(), lr=0.01)
for step in range(3000):
loss = ((net(x) - y) ** 2).mean()
opt.zero_grad(); loss.backward(); opt.step()
max_err = (net(x) - y).abs().max().item()
print(f"width {width:2d}: max error {max_err:.3f}")
# width 2: max error 1.095
# width 8: max error 0.175
# width 32: max error 0.035
The trained 8-neuron network reaches 0.175, worse than the 0.070 we built by hand. It also places its hinges wherever training happened to leave them. That gap between "exists" and "found by training" is limit number 2 in action. Wider networks close it, which is one reason overparameterised networks are easier to train.
Finally, depth. This counts the straight pieces produced by stacking the tent function:
import numpy as np
relu = lambda z: np.maximum(0, z)
tent = lambda x: 2 * relu(x) - 4 * relu(x - 0.5) # 2 ReLUs: up then down on [0, 1]
x = np.linspace(0, 1, 2**12 + 1)
y = x.copy()
for depth in range(1, 7):
y = tent(y) # one more layer
pieces = np.sum(np.abs(np.diff(np.sign(np.diff(y)))) > 0) + 1
print(f"{depth} layers, {2*depth:2d} ReLUs -> {pieces:3d} straight pieces")
# 1 layers, 2 ReLUs -> 2 straight pieces
# 2 layers, 4 ReLUs -> 4 straight pieces
# ...
# 6 layers, 12 ReLUs -> 64 straight pieces
Common pitfalls
- "Neural networks can learn anything." They can represent any continuous function given enough neurons. Whether you have enough data, compute and the right training setup to learn it is a separate question, and usually the harder one.
- Expecting extrapolation. A ReLU network is piecewise linear, so far outside its training range it just continues in straight lines. Never trust a network's predictions far from the data it saw.
- Going wide instead of deep. For complex data such as images, text and audio, a deeper network with the right architecture usually beats a wider shallow one with the same number of parameters.
- Going deep without the right tools. Before Residual Connections, normalisation and good initialisation, very deep networks were hard to train at all. Depth helps only if gradients can flow. See Vanishing and Exploding Gradients.
Watch out "Universal approximator" is not a reason to choose a neural network. Polynomials, decision trees and many other model families are universal approximators too. On small tabular datasets, gradient-boosted trees still often beat neural networks. Choose the model by what works on held-out data.
Where it leads
- Backpropagation: how gradient descent actually finds the weights in a deep network.
- Vanishing and Exploding Gradients and Residual Connections: what made depth trainable in practice.
- Convolutional Neural Networks and The Transformer: architectures whose inductive biases suit images and sequences.
- Interpretability and Explainability and Mechanistic Interpretability: looking inside the learned representations.
- Scaling Laws: the empirical rules for how performance improves with size, which matter more in practice than the existence theorems.
A bit of history
George Cybenko published the first widely cited universal approximation theorem in 1989, for networks with sigmoid activations. Hornik, Stinchcombe and White published a more general result the same year, and Hornik showed in 1991 that any bounded, non-constant activation works. In 1993, Moshe Leshno and colleagues proved that any non-polynomial activation works. Andrew Barron also showed in 1993 that for certain smooth functions, the number of neurons needed does not have to blow up with the number of inputs.
Interest then moved to depth. Results by Matus Telgarsky (2016) and by Ronen Eldan and Ohad Shamir (2016) proved that some functions need exponentially more neurons in a shallow network than in a deep one. Meanwhile, practical deep learning ran ahead of theory. In 2017, Chiyuan Zhang and colleagues showed that standard image networks can perfectly memorise images with random labels, which means classical capacity arguments can't explain why they generalise on real labels. As of late 2026, a complete theory of why deep learning works so well is still missing.
Try it
- Use
relu_netto approximate on 0 to 2 instead of (changefand the knot range). How many neurons do you need for a max error below 0.01?- Evaluate
relu_net(16)at and , outside the range it was built for. Compare with and . What happens?- Harder: build a three-layer tent network in PyTorch by setting the weights of
nn.Linearlayers by hand, and check that it outputs 8 straight pieces.Hint for 2: beyond the last knot every ramp is switched on, so the output is a straight line with the slope of the last segment.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
A visual proof that neural nets can compute any function
Chapter 4 of Neural Networks and Deep Learning. Interactive sliders let you build bumps from pairs of neurons and see universal approximation happen.
Understanding Deep Learning
A modern, beautifully illustrated textbook covering everything from basics to Transformers and diffusion, with notebooks.
Deep Learning
The classic deep learning textbook, especially strong on the maths foundations. Free to read online.
Approximation by superpositions of a sigmoidal function
One of the two original universal approximation theorems, for one-hidden-layer networks with sigmoid activations.
Multilayer feedforward networks are universal approximators
The general universal approximation theorem for feedforward networks, published in Neural Networks.
Benefits of depth in neural networks
Proves that some functions computed by deep ReLU networks need exponentially many neurons in shallow networks, using the folding construction.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/dl/universal-approximation.md