Train a tiny MLP to learn XOR
XOR is the classic problem a single linear layer cannot solve. A two-layer network can.
Write train_xor(W1, b1, W2, b2, lr, steps). The data is X = [[0,0],[0,1],[1,0],[1,1]] with targets [0,1,1,0]. The model is:
h = tanh(X @ W1 + b1), p = sigmoid(h @ W2 + b2) with W2 of shape (hidden, 1)
loss = mean binary cross-entropy.
Do full-batch gradient descent for the given steps and return (final_loss, predictions) where predictions is p rounded to 0 or 1 as a list of ints, computed after training.
def train_xor(W1, b1, W2, b2, lr, steps)Understand the idea
XOR outputs 1 when exactly one input is 1. No single straight line separates those points, so a linear model fails, but one hidden tanh layer can bend the space enough. Training repeats forward pass, gradients, update. With sigmoid output and mean binary cross-entropy, the output gradient is simply (p - y) / n. Worked example at the very start: if all four predictions are p = 0.5, the loss is log 2 = 0.693, and with y = [0, 1, 1, 0] the output gradient is (p - y) / 4 = [0.125, -0.125, -0.125, 0.125]. That gradient flows back: dW2 = h^T dz2, db2 = sum dz2, dh = dz2 W2^T, then through tanh multiply by (1 - h^2), then dW1 = X^T dpre, db1 = sum. Both layers must be updated each step; training only the output layer cannot learn XOR reliably. Rule: full-batch gradient descent for the given steps, then round final p to 0 or 1. This is the classic first test that a backprop implementation works.