Skip to content
AgenticAIWiki
  1. Learn
  2. Part 1
  3. 9. Machine learning basics for LLM builders
  4. 9.5

Lesson 9.5 · 5 of 5 · 8 min read · Reviewed 24 Nov 2026

Lab: a tiny two-layer network by hand

By the end, you can

  • Run a forward pass, a loss, a backward pass and an update for a two-layer network by hand.
  • Trace how the output error flows back to a first-layer weight through the chain rule.

Frameworks hide backpropagation behind one call. Doing it once by hand, on a network small enough to fit on a napkin, turns it from magic into bookkeeping. The lab below does exactly this in plain Python lists, with no libraries.

The network

Two inputs, two hidden neurons with ReLU, one output with sigmoid. The task: say whether a point (x1, x2) lies above the line x1 + x2 = 1 (target 1) or below it (target 0).

h1 = relu(w11*x1 + w12*x2 + b1)
h2 = relu(w21*x1 + w22*x2 + b2)
y  = sigmoid(v1*h1 + v2*h2 + c)
loss = -log(y)        if target is 1
       -log(1 - y)    if target is 0

That is 9 parameters: 4 hidden weights, 2 hidden biases, 2 output weights, 1 output bias.

One step with real numbers

Start with w1 = [0.5, -0.3], b1 = 0.1, w2 = [-0.2, 0.4], b2 = 0.1, v = [0.6, -0.4], c = 0. Example: x = (1, 0.5), target 1.

Forward pass

Value Working Result
z1 0.5 x 1 - 0.3 x 0.5 + 0.1 0.45, so h1 = 0.45
z2 -0.2 x 1 + 0.4 x 0.5 + 0.1 0.10, so h2 = 0.10
z out 0.6 x 0.45 - 0.4 x 0.10 0.23
y sigmoid(0.23) 0.557
loss -log(0.557) 0.585

Backward pass. With a sigmoid and cross-entropy, the error at the output is just d = y - target = -0.443. From there each gradient is a short product:

Gradient Rule Value
v1 d x h1 -0.199
v2 d x h2 -0.044
c d -0.443
signal into h1 d x v1 -0.266
w11 signal x relu slope (1) x x1 -0.266
w12 signal x relu slope (1) x x2 -0.133

The signal into h2 is d x v2 = +0.177: because v2 is negative, making h2 smaller would help, so w21 and w22 get positive gradients and will shrink.

Update with learning rate 0.5: v1 goes from 0.6 to 0.70, w11 from 0.5 to 0.63, c from 0 to 0.22, and so on. Run the forward pass again and y rises to 0.678; the loss drops from 0.585 to 0.388. One step, measurably better.

What to notice

  • The error flows backwards along the same paths the input flowed forwards, scaled by each weight on the way. That is the chain rule, applied mechanically.
  • Dead paths pass nothing. If z2 had been negative, ReLU’s slope would be 0 and w21, w22, b2 would not change on this example.
  • Values from the forward pass are reused. You need h1, h2 and each z to compute the gradients, which is why training stores activations and needs extra memory (lesson 9.4).

In the lab

You will write forward, backward and update with lists, train on eight points for a few hundred epochs, and print the loss falling and the final accuracy. Then try two experiments: set the learning rate to 5 and watch the loss misbehave, and start every weight at exactly 0 to see why networks need random starting weights (both hidden neurons stay identical, or never switch on).

Key points

  • One training step is always the same four moves: forward pass, loss, backward pass, update.
  • With a sigmoid output and cross-entropy loss, the error signal at the output is simply prediction minus target.
  • A hidden weight's gradient is that error, times the output weight it passes through, times the ReLU's slope, times its input.
  • A ReLU that outputs 0 passes no gradient back, so its incoming weights don't change on that example.
Hands-on labRuns in the Playground

Train a two-layer network by hand

Write the forward pass, backward pass and update for a 2-2-1 network in plain Python lists, then train it.

You will have: A training script with no libraries that reproduces the lesson's one-step numbers and reaches full accuracy.

Steps

  1. Read forward: two ReLU neurons, then a sigmoid output, all with plain lists.
  2. Fill in backward: output gradients from d = y - target, then hidden gradients through v and the ReLU slope.
  3. Fill in update: subtract learning rate times gradient from every weight and bias.
  4. Run it and check the one-step line matches the lesson: 0.585 to 0.388.
  5. Train for 300 epochs and watch the loss fall and the accuracy reach 8/8.
  6. Read the two experiments: learning rate 5.0, and every weight starting at zero.

Done when

  • The one-step check prints 0.585 -> 0.388.
  • Final accuracy is 8/8 with learning rate 0.5.
  • The all-zero start leaves the hidden weights at zero, and you can explain why.

Open in the Playground No API key needed.

Starter code (Python)
import math

# A 2-2-1 network in plain Python lists: two inputs, two ReLU hidden neurons, one sigmoid output.
# Task: is the point above the line x1 + x2 = 1? (target 1 = above, 0 = below)
DATA = [((1.0, 0.5), 1), ((0.9, 0.9), 1), ((0.2, 1.1), 1), ((1.2, 0.1), 1),
        ((0.1, 0.2), 0), ((0.4, 0.3), 0), ((0.0, 0.7), 0), ((0.6, 0.1), 0)]

def new_params():
    # The lesson's starting weights.
    return {"W": [[0.5, -0.3], [-0.2, 0.4]], "b": [0.1, 0.1], "v": [0.6, -0.4], "c": 0.0}

def sigmoid(z):
    return 1 / (1 + math.exp(-z))

def forward(p, x):
    z = [p["W"][j][0] * x[0] + p["W"][j][1] * x[1] + p["b"][j] for j in range(2)]
    h = [max(0.0, zj) for zj in z]
    y = sigmoid(p["v"][0] * h[0] + p["v"][1] * h[1] + p["c"])
    return z, h, y

def loss_of(y, t):
    y = min(max(y, 1e-9), 1 - 1e-9)
    return -math.log(y) if t == 1 else -math.log(1 - y)

def backward(p, x, t, z, h, y):
    d = y - t                                     # error at the output (sigmoid + cross-entropy)
    # TODO: output gradients: v[j] gets d * h[j], c gets d.
    g = {"v": [0.0, 0.0], "c": 0.0}
    # TODO: hidden signal[j] = d * v[j] * (1 if z[j] > 0 else 0), then
    #       W[j][i] gets signal[j] * x[i] and b[j] gets signal[j].
    g["W"] = [[0.0, 0.0], [0.0, 0.0]]
    g["b"] = [0.0, 0.0]
    return g

def update(p, g, lr):
    # TODO: subtract lr * gradient from every weight and bias in p (W, b, v and c).
    pass

def mean_loss(p):
    return sum(loss_of(forward(p, x)[2], t) for x, t in DATA) / len(DATA)

def accuracy(p):
    return sum((forward(p, x)[2] > 0.5) == (t == 1) for x, t in DATA)

# 1. One step on one example, to check against the lesson's table.
p = new_params()
x, t = DATA[0]
z, h, y = forward(p, x)
before = loss_of(y, t)
update(p, backward(p, x, t, z, h, y), 0.5)
after = loss_of(forward(p, x)[2], t)
print(f"one step: {before:.3f} -> {after:.3f}")

# 2. Train on all eight points.
def train(p, lr, epochs, report=()):
    for epoch in range(epochs + 1):
        if epoch in report:
            print(f"epoch {epoch:>3}  loss {mean_loss(p):.3f}  accuracy {accuracy(p)}/{len(DATA)}")
        if epoch == epochs:
            break
        for x, t in DATA:
            z, h, y = forward(p, x)
            update(p, backward(p, x, t, z, h, y), lr)
    return p

p = train(new_params(), 0.5, 300, report=(0, 50, 100, 300))
print(f"final accuracy {accuracy(p)}/{len(DATA)}")

# 3. Experiments.
big = train(new_params(), 5.0, 300)
print(f"lr 5.0: final loss {mean_loss(big):.3f}, accuracy {accuracy(big)}/{len(DATA)}")
zero = {"W": [[0.0, 0.0], [0.0, 0.0]], "b": [0.0, 0.0], "v": [0.0, 0.0], "c": 0.0}
zero = train(zero, 0.5, 300)
print(f"all-zero start: hidden weights still {zero['W']}, accuracy {accuracy(zero)}/{len(DATA)}")
Show a solution
import math

# A 2-2-1 network in plain Python lists: two inputs, two ReLU hidden neurons, one sigmoid output.
# Task: is the point above the line x1 + x2 = 1? (target 1 = above, 0 = below)
DATA = [((1.0, 0.5), 1), ((0.9, 0.9), 1), ((0.2, 1.1), 1), ((1.2, 0.1), 1),
        ((0.1, 0.2), 0), ((0.4, 0.3), 0), ((0.0, 0.7), 0), ((0.6, 0.1), 0)]

def new_params():
    # The lesson's starting weights.
    return {"W": [[0.5, -0.3], [-0.2, 0.4]], "b": [0.1, 0.1], "v": [0.6, -0.4], "c": 0.0}

def sigmoid(z):
    return 1 / (1 + math.exp(-z))

def forward(p, x):
    z = [p["W"][j][0] * x[0] + p["W"][j][1] * x[1] + p["b"][j] for j in range(2)]
    h = [max(0.0, zj) for zj in z]
    y = sigmoid(p["v"][0] * h[0] + p["v"][1] * h[1] + p["c"])
    return z, h, y

def loss_of(y, t):
    y = min(max(y, 1e-9), 1 - 1e-9)
    return -math.log(y) if t == 1 else -math.log(1 - y)

def backward(p, x, t, z, h, y):
    d = y - t                                     # error at the output (sigmoid + cross-entropy)
    g = {"v": [d * h[0], d * h[1]], "c": d}
    signal = [d * p["v"][j] * (1.0 if z[j] > 0 else 0.0) for j in range(2)]  # chain rule through v and ReLU
    g["W"] = [[signal[j] * x[0], signal[j] * x[1]] for j in range(2)]
    g["b"] = signal
    return g

def update(p, g, lr):
    for j in range(2):
        for i in range(2):
            p["W"][j][i] -= lr * g["W"][j][i]
        p["b"][j] -= lr * g["b"][j]
        p["v"][j] -= lr * g["v"][j]
    p["c"] -= lr * g["c"]

def mean_loss(p):
    return sum(loss_of(forward(p, x)[2], t) for x, t in DATA) / len(DATA)

def accuracy(p):
    return sum((forward(p, x)[2] > 0.5) == (t == 1) for x, t in DATA)

# 1. One step on one example, to check against the lesson's table.
p = new_params()
x, t = DATA[0]
z, h, y = forward(p, x)
before = loss_of(y, t)
update(p, backward(p, x, t, z, h, y), 0.5)
after = loss_of(forward(p, x)[2], t)
print(f"one step: {before:.3f} -> {after:.3f}")

# 2. Train on all eight points.
def train(p, lr, epochs, report=()):
    for epoch in range(epochs + 1):
        if epoch in report:
            print(f"epoch {epoch:>3}  loss {mean_loss(p):.3f}  accuracy {accuracy(p)}/{len(DATA)}")
        if epoch == epochs:
            break
        for x, t in DATA:
            z, h, y = forward(p, x)
            update(p, backward(p, x, t, z, h, y), lr)
    return p

p = train(new_params(), 0.5, 300, report=(0, 50, 100, 300))
print(f"final accuracy {accuracy(p)}/{len(DATA)}")

# 3. Experiments.
big = train(new_params(), 5.0, 300)
print(f"lr 5.0: final loss {mean_loss(big):.3f}, accuracy {accuracy(big)}/{len(DATA)}")
zero = {"W": [[0.0, 0.0], [0.0, 0.0]], "b": [0.0, 0.0], "v": [0.0, 0.0], "c": 0.0}
zero = train(zero, 0.5, 300)
print(f"all-zero start: hidden weights still {zero['W']}, accuracy {accuracy(zero)}/{len(DATA)}")
Quick checkIn one example, a hidden ReLU neuron's sum z is -0.3. What happens to the weights feeding into that neuron on this step?
How sure are you?
Pick an answer and how sure you are

Finished the chapter? Take the chapter check.