Simple Algorithm
Machine Learning · Initialization · 18 min

Neural Networks

Layers of simple units that learn their own features.

One artificial neuron cannot compute "one or the other, but not both", and the proof takes two sentences. Add a second layer and the problem disappears. Stack many layers, tune every connection from examples, and the result transcribes speech, sorts photographs and translates text. This lesson builds that machine one neuron at a time and asks where its power comes from, and what it costs.

What you’ll learn

  • Compute a neuron's output from its weights, bias and activation, and explain why one neuron can only separate classes with a straight line.
  • Prove that no single neuron computes XOR, and build a two-layer network that does.
  • Describe how a network learns: a loss, gradient descent, and backpropagation's use of the chain rule.
  • Explain what width and depth add, why large networks can memorize their training data, and how regularization fights back.
  • Trace the history from McCulloch and Pitts to AlexNet, and explain how architectures build in assumptions about the data.

A neuron weighs the evidence

Suppose you want a rule that flags a loan application as risky from two numbers: x1x_1, the applicant's debt as a fraction of income, and x2x_2, the number of payments they missed last year. A natural rule weighs each number by how much it matters, adds a constant, and checks the sign:

z=w1x1+w2x2+b,flag the application if z>0.z=w_1x_1+w_2x_2+b,\qquad\text{flag the application if }z>0.

That is an artificial neuron. The weights w1,w2w_1,w_2 say how strongly, and in which direction, each input pushes; the bias bb sets how much total evidence is needed before the neuron fires. In general a neuron takes dd inputs, forms the weighted sum z=w1x1+⋯+wdxd+bz=w_1x_1+\dots+w_dx_d+b (written compactly as z=w⊤x+bz=\mathbf w^\top\mathbf x+b), and passes it through an activation function φ\varphi to produce its output a=φ(z)a=\varphi(z). With the hard threshold "output 1 if z>0z>0, else 0" it is Rosenblatt's perceptron.

Where is the neuron undecided? Exactly on the set w1x1+w2x2+b=0w_1x_1+w_2x_2+b=0, a straight line in the plane (a flat hyperplane when there are more inputs). Every point on one side fires and every point on the other side does not, so a single neuron's decision boundary is always straight. The weights tilt the line; the bias slides it.

Check your understanding

A neuron has weights w1=w2=−2w_1=w_2=-2 and bias b=3b=3, and it fires when z>0z>0. Which logic gate does it compute on inputs from {0,1}2\{0,1\}^2?

  1. AND
  2. OR
  3. NAND
  4. XOR
Show the answer

C. NAND

z=3z=3 at (0,0)(0,0) and z=1z=1 at (0,1)(0,1) and (1,0)(1,0), so it fires on all three; at (1,1)(1,1), z=−4+3=−1z=-4+3=-1 and it stays silent. Output 0 only when both inputs are 1: that is NAND. Every logic circuit can be built from NAND gates alone, so networks of such neurons can compute any Boolean function, which was McCulloch and Pitts's point.

XOR: where one line fails

Now take XOR, short for "exclusive or": the output is 1 if one input is on but not both. On the unit square its 1s are the corners (0,1)(0,1) and (1,0)(1,0), and its 0s are (0,0)(0,0) and (1,1)(1,1), the two ends of the other diagonal.

No line separates them, and the proof takes two sentences. The points on one side of a line form a convex set: the midpoint of two points on that side lies on that side too. A line with (0,1)(0,1) and (1,0)(1,0) on its firing side would put their midpoint (12,12)(\tfrac12,\tfrac12) there as well, but (12,12)(\tfrac12,\tfrac12) is also the midpoint of (0,0)(0,0) and (1,1)(1,1), which must both be on the silent side. Contradiction: XOR is not linearly separable.

The way out is to use more than one neuron. XOR means "at least one input is on, but not both": the AND of an OR and a NAND. Give a hidden layer two neurons, h1h_1 computing OR and h2h_2 computing NAND, and let an output neuron compute the AND of h1h_1 and h2h_2:

x1x_1x2x_2h1h_1 (OR)h2h_2 (NAND)output: AND of h1,h2h_1,h_2
00010
01111
10111
11100
With threshold activations: h1h_1 fires when x1+x2−0.5>0x_1+x_2-0.5>0, h2h_2 when −x1−x2+1.5>0-x_1-x_2+1.5>0, and the output when h1+h2−1.5>0h_1+h_2-1.5>0. The last column is XOR.
Think first Plot the four inputs at their new coordinates (h1,h2)(h_1,h_2). Why can a single line now finish the job?

(0,0)(0,0) lands at (0,1)(0,1) and (1,1)(1,1) at (1,0)(1,0), while both (0,1)(0,1) and (1,0)(1,0) land on the same point (1,1)(1,1). The two positive inputs have merged, and the line h1+h2=1.5h_1+h_2=1.5 cuts (1,1)(1,1) off from the other two. The hidden layer did not solve the problem by itself: it re-described the inputs with new features in which a straight line suffices. That is what hidden layers do in every network.

Let the network learn its features

Hand-designing hidden neurons does not scale to an image with a million pixels. The fix is to make every weight learnable, those of the hidden layers included. That takes one change. A hard threshold jumps from 0 to 1, so a small change in a weight either does nothing or flips the output, and there is no slope to follow. Learning needs outputs that respond smoothly, so networks use smooth activations such as the sigmoid 1/(1+e−z)1/(1+e^{-z}), tanh⁡z\tanh z, or the ReLU max⁡(0,z)\max(0,z), which is smooth everywhere except at one point.

Layers of such neurons, each feeding the next, form a multilayer perceptron (MLP), the basic neural network. Layers that sit between the input and the output are called hidden layers. Their number is the network's depth (some authors also count the output layer), and the number of neurons in a layer is its width.

Check your understanding

Why did the network with the linear activation fail, even though it has a hidden layer of four neurons?

  1. Four neurons are too few; with forty it would succeed
  2. A linear function of a linear function is linear, so the whole network computes w1x1+w2x2+bw_1x_1+w_2x_2+b and its boundary is one straight line
  3. The learning rate was too small for a linear network
  4. Linear neurons cannot have negative weights
Show the answer

B. A linear function of a linear function is linear, so the whole network computes w1x1+w2x2+bw_1x_1+w_2x_2+b and its boundary is one straight line

Each layer computes Wx+bW\mathbf x+\mathbf b, and composing two such maps gives W2(W1x+b1)+b2=(W2W1)x+(W2b1+b2)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), another map of the same kind. However many layers you stack, without a nonlinearity between them the network is one linear model, and XOR defeats every linear model.

Learning: downhill on the loss

How does the network find good weights? Training picks a loss, a single number scoring how badly the network does on the training set, and pushes it down step by step. For classification the usual loss is the cross-entropy: if the network gives the correct class probability pp, it pays −log⁡p-\log p, which is near 0 when pp is near 1 and grows without bound as p→0p\to0.

To lower the loss, move every weight a little against its slope, the partial derivative ∂L/∂w\partial L/\partial w:

w ← w−η ∂L∂w.w\ \leftarrow\ w-\eta\,\frac{\partial L}{\partial w}.

This is gradient descent, and η\eta is the learning rate. In practice each step estimates the gradient from a mini-batch of randomly chosen examples instead of the whole training set, which is stochastic gradient descent.

The hard part is getting the derivatives. A modern network has millions or billions of weights, and the loss depends on each one through every layer above it. Backpropagation computes all of them with the chain rule. A forward pass computes and stores every neuron's value. A backward pass then starts at the loss and walks back through the network; at each node it multiplies the node's own local derivative by the gradient already computed above it, so the work done for one layer is reused by every layer below it.

Predict before you look

A tiny "network" computes z=3wz=3w and then the loss L=z2L=z^2. At w=1w=1, what is ∂L/∂w\partial L/\partial w? Do it the backpropagation way: first ∂L/∂z\partial L/\partial z, then multiply by the local derivative ∂z/∂w\partial z/\partial w.

Show the answer

18

At w=1w=1, z=3z=3, so ∂L/∂z=2z=6\partial L/\partial z=2z=6. The local derivative of z=3wz=3w is 3, and the chain rule multiplies them: 6×3=186\times3=18. Directly: L=9w2L=9w^2 has derivative 18w18w, which is 18 at w=1w=1. Backpropagation does exactly this, node by node, for every weight at once.

Wider, deeper, and the danger of memorizing

Width and depth add capacity in different ways. A wider layer draws more lines at once. A deeper network composes: the second layer builds corners and wedges out of the first layer's lines, the third builds shapes out of those, and so on. Some functions need exponentially many neurons in a single hidden layer but only a modest number when they are spread over several layers; the Descent and Convergence lessons make that precise.

Predict before you look

A network for 2-D inputs has two hidden layers of 8 neurons and one output neuron; every neuron has one weight per input and one bias. How many parameters does it have? (You can check in the widget.)

Show the answer

105

Layer by layer: 2⋅8+8=242\cdot8+8=24, then 8⋅8+8=728\cdot8+8=72, then 8⋅1+1=98\cdot1+1=9, for 105 in total. A layer with mm inputs and kk neurons has mk+kmk+k parameters, so counts grow with the product of neighboring widths: two connected layers of 1,000 neurons already hold a million weights.

More parameters cut both ways. A large network can fit almost any training set, even one whose labels were assigned at random, so a perfect training score proves little. What counts is generalization: performance on data held out from training. When a network starts fitting noise instead of the pattern, training error keeps falling while validation error rises: overfitting. The standard defenses are forms of regularization:

  • Weight decay pulls every weight a little toward zero at each step, favoring smaller, smoother functions.
  • Dropout switches off a random subset of neurons on every training step, so no neuron can lean on a few others.
  • Data augmentation trains on flipped, cropped or slightly distorted copies of the examples, teaching invariances the task is known to have.
  • Early stopping halts training when the loss on a validation set stops improving.
Check your understanding

During training, the training loss keeps falling, while the validation loss reached its minimum at epoch 20 and has risen ever since. What is the best reading?

  1. The network is underfitting; make it larger
  2. The learning rate is too small
  3. The network has started to overfit; keep the weights from around epoch 20, or regularize more
  4. The validation set is broken: validation loss cannot rise while training loss falls
Show the answer

C. The network has started to overfit; keep the weights from around epoch 20, or regularize more

Training loss measures the fit to the training examples; validation loss estimates performance on new ones. When they move in opposite directions, the network is learning details of its training set that do not carry over. Early stopping keeps the weights from the validation minimum; weight decay, dropout, augmentation or more data postpone the turn.

Why networks took over

The core of this lesson, hidden layers trained by backpropagation, was in place by the late 1980s, and convolutional networks followed soon after; dropout and the widespread use of ReLU came only in the early 2010s. For about two decades neural networks were one method among many, and on many benchmarks kernel methods such as support vector machines did as well or better. Then, in 2012, a deep convolutional network trained on two graphics cards with 1.2 million labeled ImageNet photographs (Krizhevsky, Sutskever & Hinton) won the ImageNet classification challenge, cutting the top-5 error to 15.3% when the runner-up had 26.2%. Within a few years networks led in image recognition, speech recognition and machine translation.

Three things came together: large labeled datasets, fast parallel hardware, and architectures that build in assumptions about the data. A convolutional network assumes that nearby pixels belong together and that a pattern means the same thing wherever it appears, so it slides one small filter over the whole image instead of learning separate weights for every location. A transformer treats text as a set of tokens that exchange information through attention, with each token's position supplied explicitly. Such assumptions are an inductive bias: they make the right functions easy to find from limited data. Where data have no such structure, as in many tables of mixed numeric and categorical columns, gradient-boosted trees still often win (Trees vs Deep Learning on Tabular Data).

YearMilestone
1943McCulloch & Pitts: networks of threshold neurons compute logical functions
1958Rosenblatt's perceptron learns its weights from examples
1969Minsky & Papert's Perceptrons maps the limits of a single layer
1986Rumelhart, Hinton & Williams popularize backpropagation through hidden layers
2012Krizhevsky, Sutskever & Hinton's deep CNN (AlexNet) wins ImageNet, and deep learning takes off
Descent lessonWhat you will do there
From Perceptrons to Deep NetworksWrite the forward pass in matrix form, compare activation functions, pair output layers with losses, count parameters, and see what one hidden layer can represent.
BackpropagationDerive the backward pass layer by layer, count its cost, check gradients numerically, and see why gradients vanish or explode in deep networks.
Training Networks WellAssemble the practical recipe: initialization, optimizers and learning-rate schedules, normalization layers, regularization, and how to debug a run that will not learn.
Representations, Transfer & Inductive BiasReuse what networks learn through embeddings, transfer learning and self-supervised pretraining, and read architectures as built-in assumptions.
The Descent level supplies the derivations and algorithms behind each idea; the Convergence level proves what is known and maps what is still open.

Key takeaways

  • A neuron computes φ(w⊤x+b)\varphi(\mathbf w^\top\mathbf x+b); alone, it separates classes only along a straight line (a hyperplane in higher dimensions).
  • XOR is not linearly separable, so no single neuron computes it; a hidden layer that maps the inputs to new features fixes that.
  • Without nonlinear activations any stack of layers is one linear model. With them, one wide hidden layer can approximate any continuous function on a closed, bounded region, possibly with enormously many neurons.
  • Training takes downhill steps on a loss; backpropagation supplies the slope for every weight at once by running the chain rule backward through the network.
  • Width and depth add capacity, and large networks can memorize their training data: judge them on held-out data, and regularize with weight decay, dropout, augmentation or early stopping.
  • Networks took over perception and language once big datasets, fast hardware and architectures with the right built-in assumptions came together (AlexNet, 2012).

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

A neuron has weights w1=1w_1=1, w2=−1w_2=-1, bias b=−0.5b=-0.5, and fires when z>0z>0. Which of the four inputs in {0,1}2\{0,1\}^2 make it fire?

  1. Only (1,0)(1,0)
  2. (1,0)(1,0) and (1,1)(1,1)
  3. Every input except (0,1)(0,1)
  4. None: the bias is negative
Show the answer

A. Only (1,0)(1,0)

z=x1−x2−0.5z=x_1-x_2-0.5 is 0.50.5 at (1,0)(1,0), −0.5-0.5 at (0,0)(0,0) and at (1,1)(1,1), and −1.5-1.5 at (0,1)(0,1). Only (1,0)(1,0) clears zero, so the neuron computes "x1x_1 and not x2x_2".

Question 2

In the hand-built XOR network (OR and NAND hidden neurons, AND output), what exactly did the hidden layer contribute?

  1. It memorized the four training points
  2. It made the output neuron's boundary curved
  3. It mapped the inputs to new features (h1,h2)(h_1,h_2) in which the two classes are linearly separable
  4. It replaced the need for an output neuron
Show the answer

C. It mapped the inputs to new features (h1,h2)(h_1,h_2) in which the two classes are linearly separable

OR and NAND send both XOR-positive inputs to (1,1)(1,1) and the negatives to (0,1)(0,1) and (1,0)(1,0), where one line separates them. The output neuron is still a single linear threshold unit; the hidden layer changed the representation it sees.

Question 3

Rosenblatt's perceptron uses a hard threshold. Why do networks trained by gradient descent use smooth activations such as the sigmoid, tanh or ReLU instead?

  1. Threshold units cannot compute logic functions such as NAND
  2. Smooth activations make the whole network linear, which is easier to train
  3. Threshold units need far more memory
  4. A threshold is flat on both sides of its jump, so a small change in a weight gives gradient descent no slope to follow
Show the answer

D. A threshold is flat on both sides of its jump, so a small change in a weight gives gradient descent no slope to follow

Gradient descent follows derivatives. With a step function, nudging a weight either leaves the loss unchanged or makes it jump, so the derivative carries no information about which way to move. Smooth activations (ReLU is smooth except at one point) make the loss respond gradually, so every weight gets a useful slope.

Question 4

Why do large networks get their gradients from backpropagation rather than by nudging each weight in turn and re-measuring the loss?

  1. Backpropagation finds the global minimum of the loss
  2. One backward pass gives the derivative for every weight at the cost of a few forward passes, while nudging needs about one forward pass per weight
  3. Nudging weights one at a time gives the wrong derivatives
  4. Backpropagation does not need a loss function
Show the answer

B. One backward pass gives the derivative for every weight at the cost of a few forward passes, while nudging needs about one forward pass per weight

With a million weights, nudging them one at a time costs about a million forward passes for a single gradient. The chain rule lets the backward pass reuse each layer's gradient for all the weights below it, so the whole gradient costs about as much as a few forward passes.

Question 5

Why does a convolutional network usually need far fewer training images than a fully connected network of similar size to reach the same accuracy on photographs?

  1. Its architecture builds in locality and the same-filter-everywhere assumption, so it does not have to learn them from data
  2. It trains with a larger learning rate
  3. It has more parameters
  4. Convolution makes overfitting impossible
Show the answer

A. Its architecture builds in locality and the same-filter-everywhere assumption, so it does not have to learn them from data

A fully connected network must discover from examples that an edge in one corner is the same feature as an edge in another. A convolutional network has that knowledge built in, because one small filter is reused everywhere. This inductive bias shrinks the set of functions it has to search, which saves data, as long as the assumption fits the task.

Go deeper

Further reading

  • I. Goodfellow, Y. Bengio & A. Courville, Deep Learning (MIT Press, 2016), chapters 6–8.
  • Y. LeCun, Y. Bengio & G. Hinton, "Deep learning," Nature 521, 436–444 (2015).