1.6Neurons, layers & activation functions
A neuron is a weighted sum plus a squiggle. Stack enough of them and you can bend space into almost any shape you need.
From one formula to a brain-shaped metaphor
In the last lesson you saw how a modelModelA function with adjustable parameters that maps inputs to outputs. Training sets the parameters so the outputs are useful. with adjustable parametersParameter (weight)A number inside a model that is adjusted during training. Modern LLMs have billions to trillions of them. can be trained by gradient descentGradient descentRepeatedly nudging the parameters a small step opposite the gradient, so the loss goes downhill.. We never said much about what the model is. For almost everything in modern AI, from image classifiers to the largest chatbots, the answer is a neural networkNeural networkA model made of layers of neurons, each layer transforming the previous layer's output.: a big composition of very simple units called neuronsNeuronThe basic unit of a neural network: a weighted sum of inputs plus a bias, passed through an activation function..
The word “neuron” is borrowed from biology, and the borrowing is loose. A biological neuron collects electrical signals from thousands of others and “fires” when the total crosses a threshold. The artificial version keeps exactly one idea from that story: add up weighted inputs, then decide how strongly to respond. Everything else (spikes, timing, chemistry) is thrown away. What remains is a tiny piece of arithmetic that turns out to be extraordinarily composable.
Here is the whole thing for a neuron with two inputs and :
The weights say how much each input matters (and with what sign), the bias shifts the threshold, and is the activation functionActivation functionA nonlinear function (ReLU, GELU, sigmoid…) applied after a weighted sum. Without it, stacked layers would collapse into one linear map.. The first part, , is just a dot productDot productMultiply two vectors element by element and add up the results. It is large when the vectors point in similar directions. between the weight vector and the input vector, so a neuron measures how much the input points in the direction the neuron cares about.
Imagine a talent show judge who scores each act on two criteria, singing and dancing. She has her own priorities: singing counts triple, dancing counts once, and she’s a bit stingy, so she subtracts two points from everyone. If the total is positive she says “yes”, and the more positive it is, the more enthusiastic she sounds.
Her priorities are the weights, the stinginess is the bias, and her “how enthusiastic do I sound?” rule is the activation function. One judge can only split acts along a single straight cut (“good enough overall or not”). A layer is a panel of judges each with different priorities, and a deeper network is a second panel that listens only to the first panel’s verdicts. Committees of committees can express remarkably subtle tastes.
What one neuron can see
Because is a linear function, the set of inputs where is a straight line (in higher dimensions, a flat hyperplane). On one side is positive, on the other negative. The activation function then decides how to turn that signed distance into an output: a hard yes/no, a smooth probability, or “silent unless positive”.
Play with a single neuron below. The background color is the neuron’s output at every point of the input plane; the dashed line is , its decision boundary.
Click or drag on the plane to move the probe. The dashed line is where z = 0; the arrow is the weight vector w, which always points toward the side where z > 0. Labels 0/1 on the points are the targets. σ(z) = 1 / (1 + e^(−z)).
Things to try:
- Change only the bias. The line slides without rotating. The bias is literally an offset: it moves the threshold.
- Scale both weights up together (say from 1 to 4). The line stays put but the transition gets sharper. Large weights make a sigmoid behave like a step.
- Watch the arrow. The weight vector is always perpendicular to the boundary and points toward the “on” side.
- Click “Solve AND”, then “Solve OR”. Each is one straight cut. Now choose the XOR points: output 1 when exactly one input is 1. No matter what you do, the best a single line can manage is 3 out of 4.
That last observation has history. In 1969, Marvin Minsky and Seymour Papert’s book Perceptrons analyzed the limits of single-layer networks, and the XOR problem became the standard example of a pattern that no single neuron can represent. The way out was known in principle: use more than one layer. What was missing was an efficient way to train multiple layers, which arrived in practice with backpropagation (the next lesson).
The activation function gallery
Why not skip and just output ? Hold that thought for a moment; first, meet the usual suspects. Each one is a different answer to “how should the neuron respond to its weighted sum?”
- Step: output 1 if , else 0. This was Rosenblatt’s perceptron from the late 1950s. It’s a clean yes/no, but its slope is zero everywhere (and undefined at 0), so gradient descent gets no signal about which way to nudge the weights. Nobody trains with it today.
- SigmoidSigmoidThe S-shaped function σ(z) = 1/(1 + e^(−z)), which squashes any number into the range 0 to 1. Used to turn a score into a probability; it saturates (flattens) for large |z|. : a smooth step from 0 to 1. It gives useful gradients near zero, but flattens out on both sides. When is large the neuron is saturated and its gradient nearly vanishes. Sigmoid is still the standard way to turn a single score into a probability at the output of a model.
- Tanh: a sigmoid stretched to run from −1 to 1, centered at zero. Same saturation problem, slightly better behaved inside networks.
- ReLUReLU (rectified linear unit)The activation function max(0, z): zero for negative inputs, the identity for positive ones. Cheap, with gradient 1 when active, so it helps deep networks train. : zero for negative inputs, the identity for positive ones. Dirt cheap, and its gradient is exactly 1 whenever the neuron is active, so signals don’t shrink as they pass through. ReLU’s adoption around 2010–2012 was one of the quiet ingredients of the deep-learning boom.
- GELU: a smooth cousin of ReLU, roughly where is the standard normal CDF. It dips slightly below zero for small negative inputs instead of cutting off sharply. GELU was used in BERT and GPT-2, and smooth gated variants such as SwiGLU are common in today’s LLMs.
Layers: many neurons side by side
A layer is just many neurons that all read the same inputs, each with its own weights and bias. If a layer has 8 neurons reading 2 inputs, its weights form an matrixMatrixA rectangular grid of numbers. Multiplying a vector by a matrix applies a linear transformation such as a rotation, scaling or projection. , its biases an 8-vector , and the whole layer is one line of math:
with applied to each entry separately. If you’ve done the matrices lesson, you’ll recognize as a linear transformation of space. A layer is a linear map followed by a pointwise squash.
Stack layers and you get a multilayer perceptronMLP (feed-forward network)A multi-layer perceptron: linear layers with nonlinear activations between them. Each Transformer block contains one. (MLP): inputs → hidden layer(s) → output. “Hidden” just means “not an input or an output; something the network invents for its own use.” The demo below trains a 2 → H → 1 MLP, written in about 100 lines of plain TypeScript with no libraries, on three classic datasets that no single straight line can separate.
Background colour is the network’s predicted probability of the orange class; points are the training data, and misclassified points get a dark ring. Trained with full-batch gradient descent (momentum 0.9) and hand-written backpropagation.
Things to try:
- Circles, tanh, 8 neurons. The network quickly learns a closed, roughly round boundary. Tick show each hidden neuron’s line: each hidden neuron still only draws a straight line, and the output neuron combines those half-planes into a curved region.
- XOR. A handful of hidden neurons solves the task that defeated the single neuron above.
- Spiral. Much harder. With 2 or 3 hidden neurons the network can’t do it; with 16 it gets there in a few thousand steps. More neurons means more lines to combine, so more intricate shapes.
- Activation: none (linear). Accuracy stalls near chance on every dataset, no matter how many hidden neurons you add. That’s the most important experiment on this page.
- Learning rate. On the spiral with 16 neurons, compare η = 0.02 with η = 0.5. Tiny steps crawl for thousands of iterations; on this small, well-behaved problem bigger steps simply get there sooner. On harder problems the same knob makes training blow up, exactly as in gradient descent.
Why the nonlinearity is non-negotiable
Here’s the punchline of experiment 4. Without an activation function, each layer computes . Feed that into a second linear layer:
Two linear layers collapse into one. So do ten, or a thousand. A “deep” network with no nonlinearities is mathematically identical to a single neuron per output, and can only draw straight boundaries, no matter how many parameters it has. All that extra compute buys you nothing.
The nonlinearity breaks the collapse. Geometrically, each ReLU layer folds space along its neurons’ lines: everything on the negative side of a neuron’s line gets squashed flat onto zero for that neuron. The next layer then draws straight lines in this folded space, and those lines look bent and piecewise when mapped back to the original inputs. Stack several layers and the folds compound. That’s why a ReLU network’s decision regions are made of many straight segments: the number of distinct linear pieces can grow very quickly with depth.
How expressive can this get?
Remarkably expressive. The universal approximation theoremUniversal approximation theoremThe result that a network with one hidden layer, a suitable nonlinear activation and enough neurons can approximate any continuous function on a bounded region arbitrarily well. It guarantees existence, not trainability. (proved for sigmoid-like activations by George Cybenko and, separately, by Kurt Hornik, Maxwell Stinchcombe and Halbert White, both in 1989, and later extended to essentially any non-polynomial activation) says roughly:
A network with a single hidden layer and enough neurons can approximate any continuous function on a bounded region as closely as you like.
The intuition is the one you saw in the demo. Two ReLU or sigmoid neurons with opposite slopes can make a “bump”: up here, down there. Add up enough bumps of the right heights and positions, and you can trace any reasonable curve, the way you can approximate any skyline with enough Lego bricks. Michael Nielsen’s online book has a lovely visual proof built on exactly this idea (see Further reading).
So a neural network is not magic; it’s a very flexible family of functions with knobs, plus an algorithm (gradient descent) to turn the knobs. Learning a language model is the same thing at scale: an enormous composed function from a sequence of tokens to a probability distribution over the next one, with billions of weights tuned to make that function match the data.
MATH CORNER · optionalA two-neuron solution to XOR, by hand
Let’s prove that one hidden layer solves XOR by building the network ourselves. Use two ReLU hidden neurons and a linear output:
In matrix form, , , , . Check all four inputs:
| XOR | |||||||
|---|---|---|---|---|---|---|---|
| 0 | 0 | 0 | 0 | −1 | 0 | 0 | 0 |
| 0 | 1 | 1 | 1 | 0 | 0 | 1 | 1 |
| 1 | 0 | 1 | 1 | 0 | 0 | 1 | 1 |
| 1 | 1 | 2 | 2 | 1 | 1 | 0 | 0 |
Every row matches. The magic is in row 4: is the only neuron that “turns on” when both inputs are 1, and the output weight of −2 uses it to cancel . Now delete the ReLUs: , which gives 2, 1, 1, 0. That’s a linear function, and no linear function can give 0, 1, 1, 0 (the two “1” corners average to the same point as the two “0” corners, so any linear function must give the two pairs the same average).
Counting parameters. A layer mapping inputs to outputs has weights plus biases. The demo’s 2 → 8 → 1 network has parameters. A feed-forward block that expands a width of 4,096 to 16,384 and back has about million weights. Same formula, bigger numbers.
In code
An MLP in PyTorch is a few lines. nn.Linear is the part; the activation sits between layers:
import torch
from torch import nn
model = nn.Sequential(
nn.Linear(2, 8), # 2 inputs → 8 hidden neurons: 8×2 weights + 8 biases
nn.Tanh(), # the nonlinearity (try nn.ReLU() or nn.GELU())
nn.Linear(8, 1), # 8 hidden → 1 output score (a logit)
)
x = torch.tensor([[0.5, -1.2]]) # one 2-D input point
p = torch.sigmoid(model(x)) # probability of class 1
loss_fn = nn.BCEWithLogitsLoss() # binary cross-entropy on the logit
opt = torch.optim.SGD(model.parameters(), lr=0.1, momentum=0.9)
for xb, yb in loader: # mini-batches of points and 0/1 labels
loss = loss_fn(model(xb).squeeze(1), yb)
opt.zero_grad(); loss.backward(); opt.step()
Remove the nn.Tanh() line and you have built, at great expense, a single linear classifier.
- “Artificial neurons work like brain cells.” They’re inspired by them, very loosely. A real neuron has complex dynamics, spikes and chemistry; an artificial one is a dot product and a squash. Don’t read neuroscience into network behavior.
- “More layers always help.” Without nonlinearities, extra layers add literally nothing. With them, very deep networks are hard to train unless you add tricks such as residual connections and normalization (see LayerNorm & residuals).
- “The universal approximation theorem means neural networks can learn anything.” It says a suitable set of weights exists. It says nothing about finding them, how many neurons it takes, or how well the result does on unseen data.
- “ReLU is linear, so it can’t add expressive power.” ReLU is piecewise linear, and the kink at zero is exactly what lets layers fold space. A function that is linear in pieces is not linear overall.
- “Each neuron learns one human-understandable concept.” Sometimes, but often not. Neurons in real networks frequently respond to several unrelated things; see the lesson on interpretability.
Check your understanding
Q1.A single neuron with weights (w₁, w₂) and bias b uses a sigmoid activation. What shape is its decision boundary (where the output is 0.5) in the 2-D input plane?
Q2.You build a 10-layer network but forget the activation functions. What can it represent?
Q3.Why did the step function fall out of use as an activation for training networks?
Q4.What does the universal approximation theorem guarantee?
Q5.In the demo, the spiral fails with 2 hidden neurons but works with 16. Which explanation fits best?
Further reading
- bookNeural Networks and Deep Learning, Chapter 4: A visual proof that neural nets can compute any function — Michael Nielsen's interactive, bump-by-bump intuition for universal approximation.
- videoBut what is a neural network? — 3Blue1Brown's visual introduction to neurons and layers.
- codeTensorFlow Playground — A bigger browser playground: add layers, change activations, watch the regions bend.
- paperGaussian Error Linear Units (GELUs) — Hendrycks & Gimpel, the paper that introduced GELU.
- paperGLU Variants Improve Transformer — Noam Shazeer's short paper on SwiGLU and friends, the activations inside many modern LLMs.
- bookDeep Learning (Goodfellow, Bengio, Courville), Chapter 6: Deep Feedforward Networks