Neural Networks from Scratch
Generative & Agentic AI · AI Foundations · Basics · 20 min
Build a neural network in your head: neurons, layers, loss, gradient descent and backprop, with tiny numbers you can check by hand.
A huge mixing desk with millions of little knobs. Training is a robot that listens to how wrong the song sounds and gives every knob a tiny turn in the direction that makes it sound better.
The idea in everyday words
Think of a team of judges scoring a talent show. Each judge looks at a few things (singing, dancing, stage presence), cares about some more than others, and gives a score. A head judge combines their scores into the final verdict. If the verdict is wrong, everyone adjusts how much they care about each thing. A neural network is exactly that: layers of tiny judges whose 'how much I care' numbers get tuned from mistakes.
One neuron: weigh, add, squash
A neuron is a tiny calculator with three steps:
- Weigh: multiply each input by a weight (how much it matters).
- Add: sum them and add a bias (a starting nudge up or down).
- Squash: pass the total through an activation function. The most common one, ReLU, just means "if it is negative, make it 0".
Tiny example: should you go to the beach? Inputs: sunny = 1, warm = 1, homework due = 1.
| input | value | weight | value × weight |
|---|---|---|---|
| sunny | 1 | 3 | 3 |
| warm | 1 | 2 | 2 |
| homework | 1 | -4 | -4 |
Sum = 1, plus bias -1 → 0. ReLU(0) = 0, so "no beach today".
def relu(z):
return max(0, z)
def neuron(inputs, weights, bias):
z = sum(x * w for x, w in zip(inputs, weights)) + bias
return relu(z)
print(neuron([1, 1, 1], [3, 2, -4], -1)) # homework due -> 0
print(neuron([1, 1, 0], [3, 2, -4], -1)) # no homework -> 4
The key idea: a neuron is a weighted vote followed by a simple on/off-ish rule. The weights are what the network learns.
Layers: neurons working in teams
Put many neurons side by side and you get a layer. Feed one layer's outputs into the next and you get a network:
- Input layer: the raw numbers (pixels, word vectors, house sizes).
- Hidden layers: neurons that build up useful features.
- Output layer: the answer (a price, or one score per class).
Counting the knobs: a layer with 3 inputs and 4 neurons has 3 × 4 = 12 weights + 4 biases = 16 parameters. A "7B" language model has about 7 billion of these.
Why the activation matters. Without it, every layer is just "multiply and add". Stacking two of those is still "multiply and add": 2 × (3 × x) = 6 × x. A hundred layers would collapse into one. The little ReLU bend between layers is what lets depth build curved, complicated shapes.
Classic proof: XOR (output 1 when exactly one input is 1). No single neuron can draw that rule, but two hidden neurons can:
def relu(z):
return max(0, z)
for a, b in [(0, 0), (0, 1), (1, 0), (1, 1)]:
h1 = relu(a + b) # "at least one is on"
h2 = relu(a + b - 1) # "both are on"
out = h1 - 2 * h2 # one on = 1, both on = 2 - 2 = 0
print(a, b, "->", out)
Learning: loss and gradient descent
How does the network find good weights? It guesses, measures, and nudges.
- Forward pass: run the inputs through the network to get a prediction.
- Loss: one number for "how wrong". For numbers we use mean squared error = the average of (prediction − answer)².
- Gradient: for each weight, "if I increase this weight a tiny bit, does the loss go up or down, and how fast?" That slope is the gradient.
- Update: move each weight a small step against its gradient:
w = w - learning_rate * gradient. This is gradient descent: walking downhill on the loss.
Picture being blindfolded on a hill. You feel the slope under your feet and take a small step downhill. Repeat. The learning rate is your step size: too small and you take forever, too big and you leap over the valley and land higher up.
points = [(-2, -3), (-1, -1), (0, 1), (1, 3), (2, 5)] # truth: y = 2x + 1
w, b, lr = 0.0, 0.0, 0.1
for step in range(30):
gw = sum(2 * ((w * x + b) - y) * x for x, y in points) / len(points)
gb = sum(2 * ((w * x + b) - y) for x, y in points) / len(points)
w, b = w - lr * gw, b - lr * gb
if step % 6 == 0:
loss = sum(((w * x + b) - y) ** 2 for x, y in points) / len(points)
print("step", step, "w", round(w, 3), "b", round(b, 3), "loss", round(loss, 4))
Change lr to 0.6 and run it again: the loss explodes. The visual above shows exactly this.
Backprop: blame flows backwards
A real network has millions of weights. Measuring each slope by wiggling one weight at a time would take millions of forward passes. Backpropagation gets every gradient in one backward pass using the chain rule.
The intuition is blame. Start at the loss and walk backwards:
- How much did the output contribute to the error? (Its blame.)
- A weight's blame = the blame of the thing it fed × the value it multiplied.
- Pass blame back through each weight to the layer before, and repeat.
Tiny network: h = w1 * x, y = w2 * h, with x = 2, target 10, w1 = 1, w2 = 3.
x, target = 2.0, 10.0
w1, w2 = 1.0, 3.0
h = w1 * x # forward: 2
y = w2 * h # forward: 6
loss = (y - target) ** 2 # 16
d_y = 2 * (y - target) # -8 blame at the output
d_w2 = d_y * h # -16 w2 multiplied h
d_h = d_y * w2 # -24 pass blame back through w2
d_w1 = d_h * x # -48 w1 multiplied x
print("loss", loss, "grads", d_w1, d_w2)
# sanity check: nudge w1 a tiny bit and measure the slope directly
eps = 1e-4
y2 = w2 * ((w1 + eps) * x)
print("numeric d_w1 ~", round(((y2 - target) ** 2 - loss) / eps, 1))
Both gradients are negative, so both weights should grow. Frameworks like PyTorch do this bookkeeping for you (it is called autograd), but now you know what it computes.
Why depth helps, and where this runs on AWS
Depth = building blocks on building blocks. In an image network, early layers spot edges, middle layers combine edges into shapes (eyes, wheels), and late layers combine shapes into objects (face, car). Each layer reuses the features below it, so a deep network can express complex ideas with far fewer neurons than one giant flat layer.
Deep networks used to be hard to train because gradients shrank to nothing (or blew up) as blame passed back through many layers. Modern fixes: ReLU-style activations, normalisation layers, residual connections (shortcuts that let blame skip layers), and good starting weights. An LLM is exactly this recipe at enormous scale: dozens of transformer layers and billions of weights, trained with gradient descent.
On AWS: you train networks with Amazon SageMaker AI training jobs (pick a GPU instance such as the P or G families, or AWS Trainium chips through the Neuron SDK), and store data in Amazon S3. For quick experiments, a SageMaker notebook is enough for everything in this lesson. Open-source equivalent: PyTorch or JAX on any GPU; on GCP, Vertex AI; on Azure, Azure Machine Learning.
Step by step
- Set up:
Tiny net: h = w1·x, y = w2·h. Input x = 2, target 10. Start with w1 = 1, w2 = 3.
- Forward pass:
h = 1 × 2 = 2, y = 3 × 2 = 6. Loss = (6 − 10)² = 16.
- Blame the output:
d_y = 2 × (6 − 10) = −8. Negative: the output should go UP.
- Blame each weight:
d_w2 = d_y × h = −16. Pass back: d_h = d_y × w2 = −24, so d_w1 = d_h × x = −48.
- Update:
Learning rate 0.01: w1 = 1 − 0.01 × (−48) = 1.48, w2 = 3 − 0.01 × (−16) = 3.16.
- Check:
New forward pass: h = 2.96, y = 9.35, loss ≈ 0.42. One step cut the loss from 16 to 0.42.
- Repeat:
Real training repeats this for millions of steps over batches of data. The recipe never changes.
Code example
# A 2-layer network that solves XOR, written neuron by neuron.
def relu(z):
return max(0, z)
def layer(inputs, W, b, activate=True):
out = []
for row, bias in zip(W, b):
z = sum(w * x for w, x in zip(row, inputs)) + bias
out.append(relu(z) if activate else z)
return out
W1, b1 = [[1, 1], [1, 1]], [0, -1] # h1 = "any on", h2 = "both on"
W2, b2 = [[1, -2]], [0]
params = sum(len(r) for r in W1) + len(b1) + sum(len(r) for r in W2) + len(b2)
print("parameters:", params)
for a, b in [(0, 0), (0, 1), (1, 0), (1, 1)]:
hidden = layer([a, b], W1, b1)
out = layer(hidden, W2, b2, activate=False)
print((a, b), "hidden", hidden, "-> xor", out[0])Complexity
- Time: O(total weights) per forward pass: every weight is used in exactly one multiply-add
- Space: O(widest layer) to hold activations at inference; training also keeps every layer's activations for the backward pass
Interview tips
"Why do neural networks need non-linear activations?" Without them, any stack of layers equals a single linear layer.
Explain backprop in two sentences: compute the loss, then use the chain rule backwards to get every weight's gradient in one pass; then step each weight against its gradient.
Know vanishing and exploding gradients and the fixes: ReLU-family activations, normalisation layers, residual connections, careful initialisation, gradient clipping.
Batch vs mini-batch vs stochastic gradient descent, and why Adam is the usual default optimiser.
Overfitting fixes: more data, dropout, weight decay, early stopping, and always a held-out validation set.
Challenge: Forward Pass of a Tiny Network
Write forward_pass(x, layers) that runs input vector x through a fully connected network and returns the output vector.
layersis a list of[W, b].Wis a list of rows: row j holds neuron j's weights (one per input).b[j]is neuron j's bias.- Each neuron computes
sum(W[j][i] * a[i]) + b[j], whereais the previous layer's output. - Apply ReLU (
max(0, z)) on every layer except the last. - With no layers, return
xunchanged.
Example:
forward_pass([1, 2], [ [[[1, 1], [1, -1]], [0, 0]], [[[1, 1]], [0]] ]) → [3]
Hidden sums are [3, -1] → ReLU → [3, 0]; the output neuron gives 3 + 0 + 0 = 3.
Solve it in the browser with tests, hints and an AI coach.
Practice problems
- TensorFlow Playground: train a network in your browser
- 3Blue1Brown: Neural networks (visual series)
- micrograd: backprop engine in ~100 lines (Karpathy)
- Dive into Deep Learning (free book)
More in AI Foundations
- Machine Learning in 15 Minutes
- What Is GenAI? LLMs & Tokens
- Tokenization & Byte-Pair Encoding
- Transformers & Attention
- How LLMs Are Trained: Pretraining, SFT & RLHF
- Reasoning Models & RL Post-Training
Previous: Machine Learning in 15 Minutes · Next: What Is GenAI? LLMs & Tokens