Neural Networks from Scratch: Neurons, Loss, Backpropagation, Training Loop
Network Anatomy
Circles in a network diagram -> Neurons (also called parameters). Smallest unit of the architecture.
- Input layer - where data enters
- Hidden layers - everything between input and output; there can be n of them; most neurons live here
- Output layer - where the prediction comes out
- "GPT has 1 trillion parameters" refers to these neurons and their connections
Learning as Guess, Error, Adjust
Example
Data: 1000 sq ft -> $200K, 1500 -> $300K, 2000 -> $400K. Price of 2500 sq ft? Humans spot the pattern ($200 per sq ft) and say $500K.
- 1) Start with a random guess (say $1M)
- 2) Measure the error (off by $500K)
- 3) Adjust parameters using that feedback
- 4) Repeat (guess $500K, error 0). Real training repeats thousands to billions of times
Human version: you answer 2+2=5, teacher says wrong, answer is 4. You adjust. Same loop.
What a Neuron Does
A neuron is a plain mathematical function, like sum or subtraction. Not a biological neuron.
- Takes inputs X (e.g. house size)
- Multiplies each by its weight W
- Sums them (plus bias B)
- Passes the result through an activation function
- Inputs stay fixed. Weights are what change during learning.
- Weight -> importance score for that input. Near 1 means pay attention, near 0 means ignore.
- Weights start random.
- Bias - extra learnable term added per neuron. Gives the model more room to learn.
Example
Input 1000 with weight 0.1 gives 100. Do the same for every input, then sum.
The Linearity Problem and Activation Functions
The Problem
- Layer 1: y = W1·x + b1. Layer 2: z = W2·y + b2.
- Substitute: z = W2W1·x + (W2b1 + b2)
- Call W2W1 = W' and W2b1+b2 = b'. Result: z = W'x + b'. Same form as a single layer.
Two layers collapse into one. A million layers also collapse into one. Depth gives nothing. (Linearity Problem)
Visual intuition: red and blue points that no single straight line can separate. A line with bends can.
The Solution
- Activation function - adds non-linearity (bends) after each neuron
- Each layer bends in a different place, so layers can't collapse
- Neuron decides whether to fire or not
- Missing before ~1970s; its absence is linked to the early AI winter
Interview favourite: why do we need activation functions? Without them any depth collapses into one linear layer.
Common Activation Functions
| Function | Behaviour |
|---|---|
| Sigmoid | Squashes to range 0 to 1; too restrictive |
| Tanh | Range -1 to 1; more room but still had problems |
| ReLU | Negative input -> 0; positive input -> same number (-2 gives 0, 2 gives 2) |
| GELU / ELU | ReLU-like with smoother tweaks (small negative values instead of hard zero) |
Whichever function performs best across huge numbers of experiments becomes the industry standard. ReLU was standard for a long time.
Loss Function
Loss function - single number measuring how wrong the model is. Lower is better. Training goal -> minimise loss.
- Squaring makes every error positive
- Big errors get penalised much more
Example
Actual $400K, predicted $350K, error 50K, squared error is large. Predict 410K, error 10K, much smaller. Predict 400K, loss 0 -> learned.
Backpropagation, Forward and Backward Pass
After computing loss, the network needs to know which weights to change. Backpropagation -> assigns blame to weights.
Example
Profit drops. CEO asks deputy CEO, who asks managers, who ask employees. The report flows back and finds employee 3 responsible. Likewise the loss flows back and finds neuron 3's weight responsible.
- Forward pass - data travels input -> hidden -> output -> loss
- Backward pass - loss travels back to find responsible weights
- Error flows backwards, not forward
- Same for GPT, Claude, image models
The lecture treats it as intuition only. The calculus is partial differentiation, to be covered later if needed.
Loss Landscape, Learning Rate, Gradient Descent
Loss landscape -> visualising loss for all weight settings as hills and valleys. Training starts at a random point and must reach the lowest valley.
- Backpropagation -> tells which direction to move
- Learning rate -> how big each step is
- Too high - overshoots and bounces around, may never reach the minimum
- Too low - gets there but takes very many steps
- Medium - reaches minimum in few steps
Analogy: blindfolded on a hill. Gravity under your feet shows the downhill direction (backprop). Your step size is the learning rate.
Hyperparameter - setting a human chooses (learning rate, iterations). Weights are changed by backprop; hyperparameters are not.
Gradient descent - the full algorithm of stepping downhill using the backprop direction and the learning rate.
The Full Training Loop
Scale this to a billion-parameter network and a big chunk of internet text, repeat millions of times, and you get an LLM.
Coding the XOR Network in NumPy
XOR problem - exclusive OR. Different inputs give 1, same inputs give 0. Not separable by one straight line, so it needs an activation function.
| x1 | x2 | target |
|---|---|---|
| 0 | 0 | 0 |
| 0 | 1 | 1 |
| 1 | 0 | 1 |
| 1 | 1 | 0 |
- NumPy - matrices and maths in Python
- Matplotlib - plotting
- Colab notebook - run Python cell by cell
- Random seed - reproduces the same results each run
Architecture: 2 inputs -> 4 hidden -> 1 output (output is 0 or 1).
- Weights: 2x4 = 8, plus 4x1 = 4, total 12
- Biases: 4 hidden + 1 output = 5 (input layer has none)
- Total 17 parameters
Weights start random, so the first predictions are garbage and initial loss is about 0.2557.
import numpy as np
X = np.array([[0,0],[0,1],[1,0],[1,1]])
y = np.array([[0],[1],[1],[0]])
sigmoid = lambda z: 1/(1+np.exp(-z))
# forward pass
# z_h = X @ W1 + b1 ; a_h = sigmoid(z_h)
# z_o = a_h @ W2 + b2 ; out = sigmoid(z_o)
# loss = np.mean((out - y)**2)- Forward: input -> hidden (dot product + bias, sigmoid), hidden -> output (same)
- Loss: mean squared error
- Hyperparameters: learning rate 2, iterations 10,000
- After training, outputs like 0.98 round to 1; the model learns XOR
- Learning rate too high: loss stuck near 0.25. Too low: loss barely moves (0.255 to 0.251).
PyTorch Version
import torch, torch.nn as nn
X = torch.tensor([[0.,0],[0,1],[1,0],[1,1]])
y = torch.tensor([[0.],[1],[1],[0]])
model = nn.Sequential(nn.Linear(2,4), nn.Sigmoid(), nn.Linear(4,1), nn.Sigmoid())
loss_fn = nn.MSELoss()
opt = torch.optim.SGD(model.parameters(), lr=2)
for i in range(10000):
pred = model(X)
loss = loss_fn(pred, y)
opt.zero_grad()
loss.backward()
opt.step()- loss.backward() -> backward pass; no manual derivatives
- optimizer.step() -> moves weights, step size set by learning rate
- Gives the same result as the manual NumPy version
- Preferred in industry: many built-in activations and losses, automatic backprop
Glossary
- Weight
- Learnable number saying how important an input is.
- Bias
- Extra learnable number added to a neuron's weighted sum.
- Activation function
- Non-linear function applied to a neuron's output so layers do not collapse.
- ReLU
- Rectified linear unit: outputs 0 for negatives and the same number for positives.
- Loss function
- Single number measuring how wrong a prediction is.
- Backpropagation
- Algorithm that sends the loss backward to find which weights caused the error.
- Learning rate
- Hyperparameter controlling how big each weight update step is.
- Gradient descent
- Stepping downhill on the loss using backprop direction and learning rate.
- Hyperparameter
- Setting chosen by a human, such as learning rate or iterations.