How a network
learns to be less wrong
A neural network is not magic and not a brain. It is a stack of multiplications, a way of measuring error, and a rule for nudging numbers downhill. This course walks the full loop — signal forward, error backward — until every piece has a job you can name.
What you'll cover
- What a neural network actually is
- The neuron: weights, bias, activation
- Layers, depth, width and parameters
- Forward propagation: making a prediction
- Loss: putting a number on wrong
- Backpropagation and gradient descent
- Training in practice
- Beyond the basic net: CNNs, RNNs, transformers
- Best practices and common pitfalls
- Knowledge check (10 questions)
- Glossary
- Sources and further reading
What a neural network actually is
A neural network is a function. You hand it numbers, it hands numbers back. What makes it interesting is that the function contains thousands or billions of adjustable dials — called parameters — and there is a mechanical procedure for turning those dials so the outputs get closer to the answers you wanted.
That is the entire idea. Everything else in this course is detail about the shape of the function (modules 2–4), how you measure "closer" (module 5), and how you turn the dials (modules 6–7).
The one-sentence version
Traditional software is written rule by rule: a human decides that if the email contains "wire transfer urgently" it goes to spam. A neural network is not written that way. You supply examples — thousands of emails already labelled spam or not — and the training procedure discovers the weighting of features that separates them. You specify the architecture and the objective; the data specifies the rules.
| Dimension | Classic programming | Neural network |
|---|---|---|
| You write | The rules, explicitly | The architecture and the objective |
| You supply | Input data | Input data and labelled examples of the right answer |
| Output | Deterministic result | A learned approximation, usually with a confidence |
| Fails by | Throwing an error | Being confidently wrong on data unlike its training set |
| Best when | Rules are known and stable | Rules are fuzzy, visual, linguistic, or too numerous to write |
Why "neural"
The vocabulary is borrowed from biology and the borrowing is loose. A biological neuron fires a spike when incoming signals cross a threshold; an artificial neuron computes a weighted sum and passes it through a smooth function. The resemblance is a historical metaphor, not a claim about the brain. It is more useful to think of a network as a very large, very flexible curve-fitter than as a digital mind.
"But what is a neural network? | Chapter 1, Deep learning" — 3Blue1Brown. Open on YouTube ↗
The neuron: weights, bias, activation
One artificial neuron does three things in order. It weights each incoming number, adds a bias, and passes the total through an activation function. That is the whole unit, and a network is nothing but many copies of it wired together.
- Inputs (x) — the numbers arriving, either raw features or activations from the previous layer.
- Weights (w) — one per input, learned. A weight is importance: large positive means "this input pushes my output up", negative means it pushes down, near zero means "ignore it". Weights are where the knowledge lives.
- Bias (b) — a learned offset added regardless of input. It shifts the threshold at which the neuron becomes active, so a neuron isn't forced to output zero when its inputs are zero.
- Activation g(z) — a fixed, non-linear function applied to the sum.
Why the activation function is non-negotiable
Without it, every neuron is a linear function, and stacking linear functions produces… another linear function. A hundred layers of pure multiplication collapse algebraically into a single equivalent layer, capable only of drawing straight lines. Non-linearity is what buys you depth. It is the ingredient that lets layers compose into curves, corners and concepts.
| Activation | Output range | Behaviour and typical use |
|---|---|---|
ReLUmax(0, z) | 0 → ∞ | Cheap, fast, the default for hidden layers. Negative inputs output exactly zero, which can leave neurons permanently "dead". |
| Leaky ReLU | −∞ → ∞ | Lets a small slope through for negatives, curing dead neurons at almost no cost. |
| Sigmoid | 0 → 1 | Squashes to a probability. Fine for a binary output layer; poor in deep hidden layers because its gradient vanishes at the extremes. |
| Tanh | −1 → 1 | Zero-centred sigmoid; better behaved than sigmoid in hidden layers but shares the saturation problem. |
| Softmax | 0 → 1, sums to 1 | Output layer for multi-class problems: turns raw scores into a probability distribution over classes. |
Turn the dials on one neuron
Move the weights and bias and watch the weighted sum and the activation respond. Try setting a weight to zero — the neuron stops listening to that input entirely.
Layers, depth, width and parameters
Neurons are organised into layers, and layers into three roles:
- Input layer — not really neurons, just the entry point. Its size is fixed by your data: 784 for a 28×28 greyscale image, one per column for a spreadsheet.
- Hidden layers — everything in between, where representation happens. Their number and size are yours to choose.
- Output layer — sized by the task: one neuron for a price or a yes/no, ten for ten digit classes.
In a fully connected (dense) network, every neuron in a layer receives every output from the layer before. Depth is how many layers you stack; width is how many neurons sit in each.
What depth actually buys
Each layer transforms the representation handed to it. In a vision network, early layers respond to edges and gradients, middle layers to textures and parts, later layers to whole objects. Nobody assigns those jobs — the hierarchy emerges because a deep network is rewarded for reusing simple features to build complicated ones. Depth is compositional efficiency: a deep narrow network often expresses with hundreds of parameters what a shallow wide one needs millions to match.
Counting parameters
Between two adjacent layers, every connection is one weight, and every neuron in the receiving layer adds one bias:
Parameter count is the honest measure of a model's size. It drives memory, training time, and how much data you need before the model starts memorising instead of generalising.
Build a network and watch the cost
Add hidden layers and neurons. The diagram redraws and the parameter count updates. Notice how widening one middle layer costs far more than adding a narrow one.
Forward propagation: making a prediction
Forward propagation is the act of pushing one example through the network from input to output. Layer by layer: multiply by the weights, add the biases, apply the activation, hand the result on. In production this is the whole job — a trained model doing inference is only ever running a forward pass.
Written for a whole layer at once, it is a single matrix multiplication, which is exactly why GPUs matter:
Every value produced along the way is an activation. Hold on to them — backpropagation in module 6 needs them.
Step through a 2-2-1 network
A tiny network with fixed weights predicts whether a customer will convert, from two inputs. Step through the arithmetic one stage at a time.
Loss: putting a number on wrong
The network has made a prediction. Now you need a single number saying how bad it was, because "improve" is meaningless until "worse" is measurable. That number comes from a loss function (the error on one example) averaged into a cost function (the error across a batch or the whole dataset).
The loss function is where you encode what you actually care about. Change it and you change what the network optimises for — it is the most consequential design choice after the data itself.
| Task | Usual loss | What it punishes |
|---|---|---|
| Regression (predict a number) | Mean squared error | Squared distance from the target — big misses hurt disproportionately, so it is sensitive to outliers. |
| Regression, noisy data | Mean absolute error / Huber | Distance without the squaring, so a few wild outliers don't dominate training. |
| Binary classification | Binary cross-entropy | Confident wrong answers, harshly. Predicting 0.99 for a negative case is punished far more than predicting 0.6. |
| Multi-class | Categorical cross-entropy | Probability mass placed on the wrong class, paired with a softmax output. |
The loss landscape
Now hold the training data fixed and imagine sweeping every parameter across every possible value, recording the cost each time. The result is a surface in a space with one dimension per parameter — millions of dimensions, but the intuition survives in three. Hills are bad parameter settings, valleys are good ones. Training is the search for a low valley, and the tool for that search is slope.
"Gradient descent, how neural networks learn | Chapter 2, Deep learning" — 3Blue1Brown. Open on YouTube ↗
Backpropagation and gradient descent
Two ideas often mashed into one word. Keep them apart:
- Backpropagation answers which direction. It computes the gradient — how much the loss would change if each individual parameter changed a little.
- Gradient descent answers what to do about it. It takes that gradient and steps every parameter a small distance in the downhill direction.
Gradient descent in one line
The derivative says which way is uphill; the minus sign turns you around; the learning rate decides how far you commit. That is the entire update rule, applied to every weight and bias in the network, over and over.
How backpropagation gets the gradient
A network is a chain of nested functions, and calculus already has a rule for differentiating those: the chain rule. Backpropagation applies it in reverse, from the loss backwards to the input, reusing each layer's result as it goes.
- Run a forward pass and keep every activation.
- At the output, compute how much the loss changes with the prediction.
- Push that sensitivity back through the output layer's activation and weights to get the gradient for those weights — and the error attributable to the layer below.
- Repeat layer by layer to the input. Each layer's blame is computed from the blame of the layer above it.
- Update every parameter using the rule above.
The efficiency is the point. Estimating each gradient by nudging parameters one at a time would take one forward pass per parameter — billions of passes. Backpropagation gets all of them in a single backward sweep, which is the algorithmic breakthrough that made deep learning feasible at all.
Roll downhill, and learn what step size costs
A single parameter, a bumpy loss curve. Step and watch the descent. Then push the learning rate past ~0.9 and watch the same algorithm blow up — the classic failure mode.
Local minima, saddles, and why it works anyway
That curve has two valleys, and descent lands in whichever one it started nearest. Real loss landscapes have vastly more, which sounds fatal and mostly isn't: in very high dimensions, points where every direction curves upward are rare, most flat spots are saddles that momentum escapes, and the many decent minima tend to perform about as well as each other. You are not looking for the global minimum. You are looking for a low valley that generalises.
Optimisers: gradient descent with better habits
- Stochastic gradient descent (SGD) — update on small random batches instead of the whole dataset. Noisier steps, far faster, and the noise itself helps escape shallow traps.
- Momentum — accumulate a running velocity so the path keeps rolling through flat regions and dampens side-to-side oscillation.
- Adam — adapts a separate effective step size per parameter using running estimates of gradient mean and variance. The pragmatic default for most work.
"What is backpropagation really doing? | Chapter 3, Deep learning" — 3Blue1Brown. Open on YouTube ↗
Training in practice
The mechanics are settled. What remains is the craft: the choices that decide whether a technically correct network is actually useful.
Split the data before you touch it
- Training set (~70%) — the examples the model learns from.
- Validation set (~15%) — held out to tune architecture, learning rate and stopping point. The model never trains on it, but you make decisions from it, so it slowly leaks into your choices.
- Test set (~15%) — touched once, at the end. It is your only honest estimate of real-world performance.
Also scale your inputs. Features on wildly different ranges — age 0–100 next to income 0–500,000 — distort the loss landscape into a steep ravine that gradient descent struggles to navigate. Standardising or normalising is a one-line fix that routinely rescues a "broken" model.
Epochs, batches and steps
| Term | Meaning | Practical note |
|---|---|---|
| Batch | The group of examples processed before one parameter update | 32–256 is typical. Larger is smoother and faster per epoch, but needs more memory and can generalise slightly worse. |
| Step / iteration | One batch: forward, backward, update | Steps per epoch = examples ÷ batch size. |
| Epoch | One full pass over the training set | Stop when validation loss stops improving, not at a round number. |
| Learning rate | Step size for each update | The single most important hyperparameter. Tune it first, on a log scale, and consider decaying it over training. |
Overfitting and underfitting
The core tension of all machine learning. Underfitting means the model is too simple to capture the real pattern — it is wrong on training and test data alike. Overfitting means it has enough capacity to memorise the training examples including their noise, so training loss keeps dropping while validation loss turns and climbs. That divergence is the signal to watch.
Find the sweet spot between too simple and too clever
Blue points are training data, red are held-out validation points. Raise model capacity and watch the fitted curve start chasing noise — training error falls while validation error turns and rises.
Regularisation: the tools that fight overfitting
- More and better data — always the strongest remedy. Data augmentation (crops, flips, noise, paraphrases) manufactures variety for free.
- Early stopping — halt when validation loss stops improving, and keep the best checkpoint. Cheap and effective.
- Dropout — randomly switch off a fraction of neurons each training step so no unit can rely on a specific partner. Disabled at inference.
- Weight decay (L2) — add a penalty on large weights, preferring smoother functions over spiky memorisation.
- Batch / layer normalisation — stabilise the distribution of activations between layers; speeds training and adds mild regularisation.
- Reduce capacity — the underrated option. A smaller model that generalises beats a bigger one that memorises.
Beyond the basic net: CNNs, RNNs, transformers
Everything so far describes a multilayer perceptron — fully connected layers, no assumptions about the data. It works, but it treats an image as an unordered list of pixels and a sentence as an unordered bag of words. The famous architectures are all variations that build a structural assumption into the wiring itself.
| Architecture | Built-in assumption | Typical use |
|---|---|---|
| MLP (dense) | None — every input relates to every other | Tabular data, small feature sets, final layers of larger models |
| CNN (convolutional) | Nearby values relate, and a useful pattern is useful anywhere in the input | Images, video, audio spectrograms, anything on a grid |
| RNN / LSTM | Order matters; carry a memory of what came before | Sequences and time series — largely superseded by transformers for language |
| Transformer | Any element may relate to any other; learn which, in parallel | Language, code, increasingly vision and audio; the basis of modern LLMs |
| Autoencoder | Compress to a bottleneck, then reconstruct | Dimensionality reduction, denoising, anomaly detection, embeddings |
Convolutional networks, briefly
Instead of a weight per pixel, a CNN learns a small filter — say 3×3 — and slides it across the whole image. Two consequences follow. The parameter count collapses, because one filter is reused everywhere rather than relearned per position. And the feature becomes translation-invariant: an edge detector trained on the top-left corner works in the bottom-right too. Stack these layers and you get the edges → textures → parts → objects hierarchy from module 3.
Transformers and attention
A transformer processes a whole sequence at once and uses attention to let every element look at every other and weigh how relevant each one is to it. In "the trophy didn't fit in the case because it was too big", attention is the mechanism that lets "it" bind to "trophy". Because there is no left-to-right recurrence, the computation parallelises across a sequence — which is precisely what made training on internet-scale text practical.
"But what is a GPT? Visual intro to transformers | Chapter 5, Deep learning" — 3Blue1Brown. Open on YouTube ↗
Best practices and common pitfalls
Practices worth making habits
- Establish a dumb baseline first — a linear model, or predicting the average. If the network can't beat it, the problem is your data or framing, not your architecture.
- Split the data before any exploration, and keep the test set sealed until the end.
- Scale and clean inputs before blaming the model. Most "the network won't learn" tickets are data problems.
- Start with the smallest architecture that could work, and grow only in response to underfitting.
- Tune the learning rate first, on a log scale (0.1, 0.01, 0.001). It outranks every other hyperparameter.
- Deliberately overfit a handful of examples as a smoke test. If the model can't memorise ten rows, the pipeline is broken.
- Plot training and validation loss every run. The shape of those two curves diagnoses nearly everything.
- Set random seeds and log hyperparameters, so a good result can be reproduced tomorrow.
- Evaluate with metrics that match the stakes — accuracy is meaningless on a 99:1 class split, where precision, recall and a confusion matrix are not.
Pitfalls that catch capable people
- Data leakage — scaling or imputing across the full dataset before splitting, or including a feature that encodes the answer. Produces beautiful validation scores and a model that fails in production.
- Judging on the test set repeatedly — every peek turns it into a second validation set and inflates your estimate.
- Chasing architecture before fixing data — more labels and cleaner labels beat a fancier model almost every time.
- Unbalanced classes ignored — 99% accuracy on a 99% negative dataset is a model that learned to say "no".
- Learning rate left at default — too high and loss oscillates or becomes NaN; too low and it crawls, or stalls in the first flat spot it meets.
- Training loss watched alone — it only ever goes down. Validation loss is the one that tells the truth.
- Assuming yesterday's distribution — the world drifts. Monitor live performance and plan to retrain.
- Treating the output as an explanation — a confidence score is not a reason. Where decisions affect people, budget for interpretability and human review.
Test yourself — 10 questions
Pick one answer per question, then score. Explanations appear with your result.
Glossary
- Neuron (unit)
- The basic component: computes a weighted sum of its inputs plus a bias, then applies an activation function.
- Weight
- A learned multiplier on one input, encoding how much that input matters. Weights hold what the network has learned.
- Bias
- A learned constant added to a neuron's weighted sum, shifting the point at which it activates.
- Activation function
- A fixed non-linear function (ReLU, sigmoid, tanh, softmax) applied to a neuron's sum. Without it, depth adds nothing.
- Parameter
- Any value learned during training — all weights and biases. Distinct from a hyperparameter, which you choose.
- Hyperparameter
- A setting fixed before training: learning rate, batch size, layer count, dropout rate.
- Forward propagation
- Passing an input through the network layer by layer to produce a prediction. Also called inference.
- Loss / cost function
- The measure of how far predictions are from targets — loss per example, cost averaged over a batch or dataset.
- Gradient
- The vector of partial derivatives of the loss with respect to every parameter: which way is uphill, and how steeply.
- Backpropagation
- The reverse-mode chain-rule algorithm that computes all those gradients in one backward sweep.
- Gradient descent
- The update rule that moves each parameter a small step against its gradient, repeatedly.
- Learning rate (η)
- How far to step on each update. Too high diverges, too low crawls or stalls.
- Epoch / batch / step
- An epoch is one full pass over the training data; a batch is the group processed before one update; a step is one such update.
- Overfitting
- Learning the training set including its noise, so validation performance degrades while training performance keeps improving.
- Regularisation
- Any technique that trades a little training accuracy for better generalisation: dropout, weight decay, early stopping, augmentation.
- Vanishing / exploding gradient
- Gradients shrinking to nothing or blowing up as they propagate through many layers, stalling or destabilising training.
Sources and further reading
- 3Blue1Brown — Neural networks series (written and video)
- Michael Nielsen — Neural Networks and Deep Learning (free book)
- Goodfellow, Bengio & Courville — Deep Learning (free online)
- Stanford CS231n — Neural networks course notes
- Google — Machine Learning Crash Course: neural networks
- TensorFlow Playground — train a network in the browser
- Andrej Karpathy — Hacker's guide to neural networks
- PyTorch — Build the neural network (tutorial)
- TensorFlow / Keras — Basic classification tutorial
- scikit-learn — Supervised neural network models
- Vaswani et al. — Attention Is All You Need (transformers)
- Distill — Zoom In: an introduction to circuits (interpretability)
- Wikipedia — Backpropagation
- Wikipedia — Universal approximation theorem