Part 09 / Topic 5 of 6
A network from scratch: XOR
XOR (output 1 when inputs differ) is the classic test: no single line separates its classes, so Part 4's logistic regression cannot learn it. One hidden layer can:
# examples/02_a_two_layer_network_learns_xor.py
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]], dtype=float)
y = np.array([[0], [1], [1], [0]], dtype=float)
rng = np.random.default_rng(0)
W1, b1 = rng.normal(0, 1, (2, 8)), np.zeros(8) # 8 hidden units
W2, b2 = rng.normal(0, 1, (8, 1)), np.zeros(1)
sigmoid = lambda z: 1 / (1 + np.exp(-z))
for step in range(5000):
h = np.tanh(X @ W1 + b1) # forward pass
out = sigmoid(h @ W2 + b2)
d_out = (out - y) / len(X) # backward pass (cross-entropy + sigmoid)
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))
# predictions: [0. 1. 1. 0.] — exactly the XOR table
Read the backward pass against section 4: d_out is the loss gradient at the output; each line multiplies by a local derivative (1 - h² is tanh's) and hands the gradient one layer back. Every deep-learning framework automates exactly these lines.
🧪 Quick quiz
- Why can a single-layer perceptron not learn XOR?
Show the answer
XOR is not linearly separable; it needs a hidden layer with a non-linearity. The two-layer network above learned it exactly.
Done here? The practice set for Part 9 — 4 exercises with solutions — is on the part page.