272. 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)Example 1
Input: train_xor([[1.0, -1.0], [-1.0, 1.0]], [0.0, 0.0], [[1.0], [1.0]], [0.0], 0.5, 200)
Output: (0.0429, [0, 1, 1, 0])
Constraints
W2has shape(hidden, 1)- Python 3 with NumPy. Code runs in your browser.
- Run checks the sample tests. Submit checks the full hidden test set (Pro).
Hint 1
With sigmoid plus BCE, dz2 = (p - y) / n.
Hint 2
Then dW2 = h.T @ dz2, dh = dz2 @ W2.T, da = dh * (1 - h ** 2), dW1 = X.T @ da.
Common mistakes
- The buggy version only trains the output layer, which is a linear model on fixed random features and cannot learn XOR reliably.
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.
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.
Topics
Companies1
- Meta the topic appears in interview reports ML system design lessons: interview-questions (rushab1)
From public interview reports and guides. Not affiliated with or endorsed by these companies.