Skip to content
LearnAI

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.

⏱ 17 minBeginner

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 x1x_1 and x2x_2:

z=w1x1+w2x2+b,a=f(z)z = w_1 x_1 + w_2 x_2 + b, \qquad a = f(z)

The weights w1,w2w_1, w_2 say how much each input matters (and with what sign), the bias bb shifts the threshold, and ff 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, w1x1+w2x2w_1 x_1 + w_2 x_2, 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.

ANALOGY· A committee of picky judges

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 z=w1x1+w2x2+bz = w_1x_1 + w_2x_2 + b is a linear function, the set of inputs where z=0z = 0 is a straight line (in higher dimensions, a flat hyperplane). On one side zz 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 z=0z = 0, its decision boundary.

INTERACTIVESingle-neuron playground
01output
Activation
z−44Sigmoid(z)
Show points
probe (x₁, x₂)
(1.50, 0.50)
z = w·x + b
2.25
output Sigmoid(z)
0.905
points on correct side
—

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)).

Drag the weight and bias sliders and watch the boundary rotate and slide. Switch activations to see the same line rendered as a hard step, a smooth ramp, or a one-sided ReLU. Then show the XOR points and try to get all four right.

Things to try:

  1. Change only the bias. The line slides without rotating. The bias is literally an offset: it moves the threshold.
  2. 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.
  3. Watch the arrow. The weight vector w=(w1,w2)w = (w_1, w_2) is always perpendicular to the boundary and points toward the “on” side.
  4. 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).

Why not skip ff and just output zz? 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?”

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 8×28 \times 2 matrixMatrixA rectangular grid of numbers. Multiplying a vector by a matrix applies a linear transformation such as a rotation, scaling or projection. WW, its biases an 8-vector bb, and the whole layer is one line of math:

h=f(Wx+b)\mathbf{h} = f(W\mathbf{x} + \mathbf{b})

with ff applied to each entry separately. If you’ve done the matrices lesson, you’ll recognize WxW\mathbf{x} 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.

INTERACTIVETrain a tiny neural network
Data
Hidden activation
0.80step 300loss vs. step
training step
0
loss (cross-entropy)
—
training accuracy
44%
parameters (2→8→1)
33

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.

Press Train and watch the decision regions bend to fit the data while the loss falls. Try the spiral with 4 vs 16 hidden neurons, then switch the activation to 'none (linear)' and watch the network fail on everything.

Things to try:

  1. 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.
  2. XOR. A handful of hidden neurons solves the task that defeated the single neuron above.
  3. 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.
  4. 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.
  5. 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 Wx+bW\mathbf{x} + \mathbf{b}. Feed that into a second linear layer:

W2(W1x+b1)+b2=(W2W1) x+(W2b1+b2)=W′x+b′.W_2(W_1\mathbf{x} + \mathbf{b}_1) + \mathbf{b}_2 = (W_2W_1)\,\mathbf{x} + (W_2\mathbf{b}_1 + \mathbf{b}_2) = W'\mathbf{x} + \mathbf{b}'.

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:

h1=ReLU(x1+x2),h2=ReLU(x1+x2−1),y^=h1−2h2.h_1 = \mathrm{ReLU}(x_1 + x_2), \qquad h_2 = \mathrm{ReLU}(x_1 + x_2 - 1), \qquad \hat y = h_1 - 2h_2 .

In matrix form, W1=(1111)W_1 = \begin{pmatrix}1 & 1\\ 1 & 1\end{pmatrix}, b1=(0,−1)\mathbf{b}_1 = (0, -1), w2=(1,−2)\mathbf{w}_2 = (1, -2), b2=0b_2 = 0. Check all four inputs:

x1x_1x2x_2z1=x1+x2z_1 = x_1+x_2h1h_1z2=x1+x2−1z_2 = x_1+x_2-1h2h_2y^=h1−2h2\hat y = h_1 - 2h_2XOR
0000−1000
01110011
10110011
11221100

Every row matches. The magic is in row 4: h2h_2 is the only neuron that “turns on” when both inputs are 1, and the output weight of −2 uses it to cancel h1h_1. Now delete the ReLUs: y^=(x1+x2)−2(x1+x2−1)=−(x1+x2)+2\hat y = (x_1+x_2) - 2(x_1+x_2-1) = -(x_1 + x_2) + 2, 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 nn inputs to mm outputs has nmnm weights plus mm biases. The demo’s 2 → 8 → 1 network has (2⋅8+8)+(8⋅1+1)=33(2\cdot 8 + 8) + (8 \cdot 1 + 1) = 33 parameters. A feed-forward block that expands a width of 4,096 to 16,384 and back has about 2×4096×16384≈1342 \times 4096 \times 16384 \approx 134 million weights. Same formula, bigger numbers.

In code

An MLP in PyTorch is a few lines. nn.Linear is the Wx+bW\mathbf{x} + \mathbf{b} 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.

COMMON MISCONCEPTIONS
  • “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

0/5 answered
  1. 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?

  2. Q2.You build a 10-layer network but forget the activation functions. What can it represent?

  3. Q3.Why did the step function fall out of use as an activation for training networks?

  4. Q4.What does the universal approximation theorem guarantee?

  5. Q5.In the demo, the spiral fails with 2 hidden neurons but works with 16. Which explanation fits best?

Further reading

Progress is saved in this browser only.
Type to search across all lessons and glossary terms.