Part 09 / Stage 3
Neural network fundamentals
Goal: Understand exactly what a neural network computes and how it learns — by building one in plain NumPy. Time: ~3 hours · Needs: Stage 1 maths (gradients, chain rule, softmax)
What you will learn
- Neurons and layers: weighted sums and activations
- Activation functions, and why non-linearity matters
- Loss functions: MSE and cross-entropy
- Backpropagation: the chain rule through a network
- A network from scratch: XOR in NumPy
- Weight initialisation
Topics in this part
Practice
Exercise 1: Forward pass by hand
For input x = [1, 2], weights W1 = [[1, -1], [0, 1]], b1 = [0, 0], ReLU activation, then W2 = [[1], [1]], b2 = [0]: compute the output on paper, then verify with NumPy.
Show the solution to Exercise 1
# Exercise 1: Forward pass by hand
import numpy as np
x = np.array([1.0, 2.0])
W1 = np.array([[1.0, -1.0], [0.0, 1.0]])
b1 = np.zeros(2)
W2 = np.array([[1.0], [1.0]])
b2 = np.zeros(1)
# By hand: x @ W1 = [1*1+2*0, 1*(-1)+2*1] = [1, 1]; ReLU -> [1, 1]; @ W2 -> 2.
h = np.maximum(0, x @ W1 + b1)
out = h @ W2 + b2
print("hidden:", h) # [1. 1.]
print("output:", out) # [2.]
Exercise 2: Starting loss
Build an untrained 10-class classifier (random logits via a zero-weight linear layer on digits features) and print its cross-entropy. Is it close to ln 10 ≈ 2.303?
Show the solution to Exercise 2
# Exercise 2: Starting loss
import math
import numpy as np
from sklearn.datasets import load_digits
X, y = load_digits(return_X_y=True)
W = np.zeros((64, 10)) # untrained: every class gets logit 0
logits = X @ W # all zeros -> uniform softmax
def cross_entropy(logits, y):
z = logits - logits.max(axis=1, keepdims=True)
log_probs = z - np.log(np.exp(z).sum(axis=1, keepdims=True))
return -log_probs[np.arange(len(y)), y].mean()
print("starting loss:", round(float(cross_entropy(logits, y)), 4))
print("ln 10 :", round(math.log(10), 4))
Exercise 3: Break the symmetry
Run the XOR network from the lesson with all-zero initial weights and print the four predictions after 5000 steps. Then print the hidden weights' column-wise spread to show all neurons stayed identical.
Show the solution to Exercise 3
# Exercise 3: Break the symmetry
import numpy as np
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]], dtype=float)
y = np.array([[0], [1], [1], [0]], dtype=float)
sigmoid = lambda z: 1 / (1 + np.exp(-z))
W1, b1 = np.zeros((2, 8)), np.zeros(8)
W2, b2 = np.zeros((8, 1)), np.zeros(1)
for _ in range(5000):
h = np.tanh(X @ W1 + b1)
out = sigmoid(h @ W2 + b2)
d_out = (out - y) / len(X)
dW2, db2 = h.T @ d_out, d_out.sum(0)
d_h = d_out @ W2.T * (1 - h ** 2)
dW1, db1 = X.T @ d_h, d_h.sum(0)
for p, g in [(W1, dW1), (b1, db1), (W2, dW2), (b2, db2)]:
p -= 1.0 * g
print("predictions:", out.ravel().round(3))
print("spread across hidden neurons (max-min per row of W1):",
(W1.max(axis=1) - W1.min(axis=1)).round(6))
# Zero spread: all 8 hidden neurons stayed identical — symmetry never broke.
Exercise 4: Gradient-check the network
Take the XOR network after 100 training steps. Pick one weight (W2[0, 0]), compute its analytic gradient from the backward pass, and compare with a numerical estimate (nudge by h=1e-5, recompute the loss).
Show the solution to Exercise 4
# Exercise 4: Gradient-check the network
import numpy as np
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]], dtype=float)
y = np.array([[0], [1], [1], [0]], dtype=float)
sigmoid = lambda z: 1 / (1 + np.exp(-z))
rng = np.random.default_rng(0)
W1, b1 = rng.normal(0, 1, (2, 8)), np.zeros(8)
W2, b2 = rng.normal(0, 1, (8, 1)), np.zeros(1)
def loss_of(W1, b1, W2, b2):
h = np.tanh(X @ W1 + b1)
out = sigmoid(h @ W2 + b2)
return float(-(y * np.log(out) + (1 - y) * np.log(1 - out)).mean())
# 100 training steps first
for _ in range(100):
h = np.tanh(X @ W1 + b1)
out = sigmoid(h @ W2 + b2)
d_out = (out - y) / len(X)
dW2, db2 = h.T @ d_out, d_out.sum(0)
d_h = d_out @ W2.T * (1 - h ** 2)
dW1, db1 = X.T @ d_h, d_h.sum(0)
for p, g in [(W1, dW1), (b1, db1), (W2, dW2), (b2, db2)]:
p -= 1.0 * g
# Analytic gradient for W2[0, 0]
h = np.tanh(X @ W1 + b1)
out = sigmoid(h @ W2 + b2)
analytic = float((h.T @ ((out - y) / len(X)))[0, 0])
# Numerical estimate
eps = 1e-5
W2[0, 0] += eps; up = loss_of(W1, b1, W2, b2)
W2[0, 0] -= 2 * eps; down = loss_of(W1, b1, W2, b2)
W2[0, 0] += eps
numerical = (up - down) / (2 * eps)
print(f"analytic : {analytic:.8f}")
print(f"numerical: {numerical:.8f}")
print("match:", np.isclose(analytic, numerical, atol=1e-6))
Mini-project: NumPy network on digits
Extend the XOR network to classify the 10-digit dataset: 64 inputs, 32 tanh hidden units, and 10 softmax outputs trained with cross-entropy. Train on 80%, print test accuracy, and verify one weight's gradient numerically.
A complete version is in solutions/mini_numpy_digits.py.
Stretch: add mini-batches and a second hidden layer, keeping the gradient check green.
Common mistakes
| Mistake | Why it is wrong | Fix |
|---|---|---|
| No activation between layers | Depth collapses to one linear map | ReLU (default) between hidden layers |
| MSE for classification | Weak gradients through softmax | Cross-entropy |
| Zero initialisation | Symmetry never breaks; nothing learns | Random init (framework defaults) |
| Deriving backprop without checking | One sign error trains garbage silently | Numerical gradient check (Part 2's tool) |
| Starting loss ignored | Misses broken init/labels on day one | Expect ~ln k at step 0 |
Quick recap
- A neuron is a weighted sum plus an activation, a layer is a matrix multiply, and a network is layers stacked.
- Non-linearity is the point: without it, depth is fake.
- Cross-entropy is the loss for classification; a completely unsure model scores ln k.
- Backpropagation is the chain rule, organised layer by layer.
- A tiny network with two inputs, eight hidden units and one output learns XOR in 42 lines; the same network initialised to zeros never does.
Checklist
- I can write the forward pass as two matrix expressions.
- I know ReLU/sigmoid/tanh shapes and when each appears.
- I can say why starting loss should be ≈ ln k.
- I traced every line of the XOR backward pass to a chain-rule step.
- I can explain the zeros-init failure in one sentence.
Read more: PyTorch quickstart (the framework version of everything here)