Machine Learning from Scratch · Neural Networks

A Tiny Network Solves XOR

One neuron can draw only one straight line, so it cannot do XOR. Add two hidden neurons, each drawing its own line, and an output neuron that combines them.

xor_network.py

# One neuron cannot do XOR. Two hidden neurons and an output neuron can.
x1s = [0, 0, 1, 1]
x2s = [0, 1, 0, 1]
wanted = [0, 1, 1, 0]            # XOR: 1 when exactly one input is 1

wa1, wa2, ba = 1.0, 1.0, -0.5    # hidden neuron A: fires if either input is 1 (OR)
wb1, wb2, bb = -1.0, -1.0, 1.5   # hidden neuron B: fires unless both are 1 (NAND)

for x1, x2 in zip(x1s, x2s):
    a = 1 if wa1 * x1 + wa2 * x2 + ba > 0 else 0
    b = 1 if wb1 * x1 + wb2 * x2 + bb > 0 else 0
    out = 1 if a + b - 1.5 > 0 else 0   # output: fires only if A and B both fire (AND)
    print(x1, x2, "->", out)

Step by step

  1. The same four input pairs as the last lesson.
  2. Second inputs. Each pair is a corner of the chart.
  3. The XOR answers: 1 when exactly one input is 1. The two points that want 1 sit on opposite corners, which is why one straight line could never separate them.
  4. Hidden neuron A: weights 1 and 1, bias −0.5. It fires when either input is on (OR). On the chart, its shaded side is everything except the corner (0, 0).
  5. Hidden neuron B: weights −1 and −1, bias 1.5. It fires unless both inputs are on (NAND). Its shaded side is everything except the corner (1, 1). Where the two shadings overlap is the band between the lines: exactly the two points XOR wants.
  6. The first example: inputs 0 and 0.
  7. Neuron A: 1 × 0 + 1 × 0 − 0.5 = −0.5, not above 0, so A says 0.
  8. Neuron B: −0 − 0 + 1.5 = 1.5, so B says 1.
  9. The output neuron gets A and B as its inputs: 0 + 1 − 1.5 = −0.5, so it says 0. Right: XOR of 0 and 0 is 0.
  10. It prints 0 0 -> 0.
  11. Inputs 0 and 1.
  12. A: 0 + 1 − 0.5 = 0.5, so A says 1.
  13. B: −0 − 1 + 1.5 = 0.5, so B says 1 too.
  14. Output: 1 + 1 − 1.5 = 0.5, so it says 1. Right!
  15. It prints 0 1 -> 1.
  16. Inputs 1 and 0.
  17. A says 1.
  18. B says 1.
  19. Output 1. Right.
  20. It prints 1 0 -> 1.
  21. Inputs 1 and 1: the case one neuron could never get right together with the others.
  22. A: 1 + 1 − 0.5 = 1.5, so A says 1.
  23. B: −1 − 1 + 1.5 = −0.5, so B says 0: it fires for everything except both on.
  24. Output: 1 + 0 − 1.5 = −0.5, so it says 0. Right: XOR of 1 and 1 is 0.
  25. It prints 1 1 -> 0.
  26. All four right: XOR solved. Each hidden neuron draws one line, and the output neuron combines them. That is the whole idea of deep learning: layers of simple neurons, each building on the one before. Real networks learn their weights instead of having them chosen by hand.