TExcelTAD
Home › Math for Deep Learning & LLMs › XOR, Depth and Universal Approximation

XOR and Why Depth Helps

XOR is the smallest problem a linear model cannot solve and the smallest a network with one hidden layer can. Working it through by hand shows what hidden layers do: they change the representation so that the final linear layer has an easy job. Depth then multiplies this power: some functions need exponentially many units in a shallow network but only a few in a deep one.

Solving XOR with one hidden layer

Two ReLU units suffice. With

h=ReLU⁡((1111)x+(0−1)),y^=h1−2h2\mathbf{h} = \operatorname{ReLU}\left(\begin{pmatrix} 1 & 1 \\ 1 & 1 \end{pmatrix}\mathbf{x} + \begin{pmatrix} 0 \\ -1 \end{pmatrix}\right), \qquad \hat{y} = h_1 - 2h_2

the four inputs map to

x\mathbf{x} h\mathbf{h} y^\hat{y}
(0,0)(0, 0) (0,0)(0, 0) 0
(0,1)(0, 1) (1,0)(1, 0) 1
(1,0)(1, 0) (1,0)(1, 0) 1
(1,1)(1, 1) (2,1)(2, 1) 0

In h\mathbf{h}-space the two inputs (0,1)(0, 1) and (1,0)(1, 0) land on the same point, and the classes become linearly separable.

python · try it yourself
import numpy as np

X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]], dtype=float)
W = np.array([[1.0, 1.0], [1.0, 1.0]]); b = np.array([0.0, -1.0]); w2 = np.array([1.0, -2.0])
H = np.maximum(0, X @ W.T + b)
print("hidden representation:\n", H)
print("outputs:", H @ w2)
hidden representation:
 [[0. 0.]
 [1. 0.]
 [1. 0.]
 [2. 1.]]
outputs: [0. 1. 1. 0.]

Learning it by gradient descent

The hand-made weights are one solution among many. A small network trained with cross-entropy finds its own. Hidden layers are not designed; they are learned.

python · try it yourself
import numpy as np

rng = np.random.default_rng(3)
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]], dtype=float); y = np.array([0, 1, 1, 0.0])
W1 = rng.normal(0, 1, (4, 2)); b1 = np.zeros(4); w2 = rng.normal(0, 1, 4); b2 = 0.0
lr = 0.5
for step in range(3001):
    A = X @ W1.T + b1; H = np.tanh(A)
    z = H @ w2 + b2; p = 1 / (1 + np.exp(-z))
    loss = -np.mean(y * np.log(p) + (1 - y) * np.log(1 - p))
    dz = (p - y) / 4                                       # cross-entropy gradient
    gw2, gb2 = H.T @ dz, dz.sum()
    dA = np.outer(dz, w2) * (1 - H**2)
    gW1, gb1 = dA.T @ X, dA.sum(0)
    W1 -= lr * gW1; b1 -= lr * gb1; w2 -= lr * gw2; b2 -= lr * gb2
    if step % 1000 == 0:
        print(f"step {step}: loss {loss:.4f}")
print("predictions:", np.round(p, 3))
step 0: loss 0.7584
step 1000: loss 0.0047
step 2000: loss 0.0023
step 3000: loss 0.0015
predictions: [0.    0.998 0.998 0.002]

The backward pass written here by hand is derived properly in Backpropagation Through an MLP.

Why depth helps

Consider the "tent" map g(x)=2ReLU⁡(x)−4ReLU⁡(x−0.5)g(x) = 2\operatorname{ReLU}(x) - 4\operatorname{ReLU}(x - 0.5) on [0,1][0, 1], made of 2 ReLU units. Composing it with itself kk times gives a sawtooth with 2k2^k linear pieces, using only 2k2k units. A one-hidden-layer network needs about one unit per kink, so it needs about 2k2^k units for the same function. Depth buys exponential expressiveness.

python · try it yourself
import numpy as np

g = lambda x: 2 * np.maximum(0, x) - 4 * np.maximum(0, x - 0.5)
x = np.linspace(0, 1, 100001)
y = x.copy()
for k in range(1, 7):
    y = g(y)
    slopes = np.sign(np.diff(y))
    pieces = 1 + np.count_nonzero(np.diff(slopes))
    print(f"depth {k} ({2 * k} ReLU units): {pieces} linear pieces")
depth 1 (2 ReLU units): 2 linear pieces
depth 2 (4 ReLU units): 4 linear pieces
depth 3 (6 ReLU units): 8 linear pieces
depth 4 (8 ReLU units): 16 linear pieces
depth 5 (10 ReLU units): 32 linear pieces
depth 6 (12 ReLU units): 64 linear pieces

Representation learning

Each layer of a trained deep network re-represents its input: edges, then textures, then object parts in a vision network; characters, then words, then syntax and meaning in a language model. This is the central idea of deep learning: learn the features instead of designing them.

In software

  • Width and depth are hyperparameters; for a fixed parameter budget, moderately deep networks usually beat very shallow ones.
  • Very deep plain networks are hard to train; residual connections fix that.
  • Probing tools inspect intermediate representations layer by layer.

Exercises

Exercise 1: Check the table

Verify the hidden representation of (1,1)(1, 1) in the hand-made XOR network.

Answer

h=(2,1)\mathbf{h} = (2, 1), y^=0\hat{y} = 0.

Solution

Pre-activations (1+1+0,1+1−1)=(2,1)(1 + 1 + 0, 1 + 1 - 1) = (2, 1); both positive, so ReLU keeps them. y^=2−2⋅1=0\hat{y} = 2 - 2 \cdot 1 = 0.

Exercise 2: Pieces from depth

How many linear pieces does the tent map composed 10 times have, and how many ReLU units does it use?

Answer

210=10242^{10} = 1024 pieces with 20 units.

Solution

Each composition doubles the number of pieces and adds 2 units.

Exercise 3: XOR with a step function (code)

Build XOR as OR⁡(x1,x2)∧¬AND⁡(x1,x2)\operatorname{OR}(x_1, x_2) \land \lnot\operatorname{AND}(x_1, x_2) using threshold units [wTx+b>0][\mathbf{w}^T\mathbf{x} + b > 0] and check all four inputs.

Answer

Hidden units OR =[x1+x2−0.5>0]= [x_1 + x_2 - 0.5 > 0] and AND =[x1+x2−1.5>0]= [x_1 + x_2 - 1.5 > 0]; output [OR−AND−0.5>0][\text{OR} - \text{AND} - 0.5 > 0].

Solution
python · try it yourself
import numpy as np
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
step = lambda v: (v > 0).astype(int)
h = step(X @ np.array([[1, 1], [1, 1]]).T + np.array([-0.5, -1.5]))
print(step(h @ np.array([1, -1]) - 0.5))
[0 1 1 0]

Test yourself

What does the hidden layer do in the XOR network?

  1. Stores the training data
  2. Maps the inputs to a representation where the classes are linearly separable
  3. Adds noise
  4. Normalizes the inputs

Composing a 2-unit tent map kk times gives how many linear pieces?

  1. 2k2k
  2. k2k^2
  3. 2k2^k
  4. kk

The main idea of representation learning is that…

  1. features are designed by hand
  2. the network learns useful intermediate features from data
  3. all layers compute the same function
  4. only the last layer matters