svish.dev

← All lessons · AI / ML · 15 min

A neuron and a tiny network from scratch

Train one neuron on AND, watch it fail on XOR, then fix it with a hidden layer — in plain NumPy.

No frameworks. Just NumPy, so every line is something you can point at. (All code on this page was run; the outputs shown are what it printed.)

One neuron

A neuron takes inputs, computes a weighted sum plus a bias, and squashes it through a sigmoid into a probability between 0 and 1.

import numpy as np

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

X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]], dtype=float)
rng = np.random.default_rng(0)

def train_neuron(y, steps=3000, lr=1.0):
    w, b = rng.normal(size=2), 0.0
    for _ in range(steps):
        p = sigmoid(X @ w + b)
        g = p - y                      # gradient of log-loss w.r.t. the pre-activation
        w -= lr * X.T @ g / len(X)
        b -= lr * g.mean()
    return np.round(sigmoid(X @ w + b), 2)

print("AND", train_neuron(np.array([0, 0, 0, 1.])))
print("XOR", train_neuron(np.array([0, 1, 1, 0.])))
AND [0.   0.01 0.01 0.99]
XOR [0.5 0.5 0.5 0.5]

AND is learned almost perfectly. XOR is stuck at 0.5 — the neuron has given up and says “I don’t know” for every input.

Why XOR breaks it

A single neuron draws one straight line through the input space. AND is separable by a line. XOR (true when exactly one input is on) puts the two “true” corners diagonally opposite — no single line splits them. No amount of training fixes that; the model simply can’t express it.

Add a hidden layer

Stack neurons: a hidden layer of 4 tanh units feeds an output neuron. Each hidden unit draws its own line; the output combines them. Training needs the slope for the first layer too, which we get by passing the error backwards — backpropagation.

def train_mlp(y, hidden=4, steps=5000, lr=0.5):
    W1, b1 = rng.normal(size=(2, hidden)), np.zeros(hidden)
    W2, b2 = rng.normal(size=hidden), 0.0
    for _ in range(steps):
        h = np.tanh(X @ W1 + b1)
        p = sigmoid(h @ W2 + b2)
        g = (p - y) / len(X)                      # output gradient
        gW2, gb2 = h.T @ g, g.sum()
        gh = np.outer(g, W2) * (1 - h ** 2)       # back through tanh
        W1 -= lr * X.T @ gh; b1 -= lr * gh.sum(0)
        W2 -= lr * gW2;      b2 -= lr * gb2
    return np.round(p, 2)

print("XOR hidden", train_mlp(np.array([0, 1, 1, 0.])))
XOR hidden [0. 1. 1. 0.]

Solved. The only new ingredient was a nonlinearity between two layers — the reason depth matters.

Exercises

  1. Change hidden to 1, then 2. What’s the smallest hidden layer that still solves XOR?
  2. Re-run with lr=5.0. Connect what you see to the gradient descent lesson.
  3. Replace tanh with ReLU (np.maximum(0, z); its slope is (z > 0)). Does it still train?

Takeaways

  • A neuron = weighted sum + nonlinearity; it can only draw one line.
  • Hidden layers + a nonlinearity let networks bend that line.
  • Backprop is just the chain rule, passing the error backwards one layer at a time.