Multilayer perceptrons: build XOR
多层感知机
Use a nine-parameter network to compute XOR exactly, track matrix shapes and separate representation from training.
multilayer-perceptronTwo simple detectors can make XOR
Two switches control a signal that should be on when exactly one switch is on. This is XOR: inputs(0,0) and(1,1) map to 0; (1,0) and(0,1) map to 1. One affine score followed by a threshold cannot separate these four corners. A small network can first detect which input is larger, then add the two positive differences.
A multilayer perceptron, or MLP, composes parameterized layers with nonlinear activations. The name does not mean that each unit is trained with the classical perceptron update. Modern MLPs commonly use differentiable or piecewise differentiable units and gradient-based training. D2L, Sections 5.1.1.2–5.1.1.3 explains hidden layers and why affine layers alone collapse; Deep Learning, Chapter 6 opening and Section 6.4 separates network composition from architecture selection.
Here we build a network by specifying its weights. There is no optimizer and no claim that training discovered those weights. First read matrix multiplication and artificial neurons.
Track shapes before counting layers
Use column vectors in this chapter. For input dimension d, hidden width h and output dimension q:
Bold h denotes the hidden vector; plain h denotes its width. Biases have h and q entries. P counts every freely trainable scalar slot, including parameters whose current value is zero. Our 2→2→1 dense network has 9 slots. It has one hidden layer and two parameterized layers. An input placeholder is not an extra affine computation. Authors count depth differently, so report the architecture as well as a layer count.
The output here is affine, appropriate for a scalar function construction. A binary probability model could add a sigmoid; a multiclass probability model could add softmax. Output choice and loss must match the task.
If φ is the identity, substitution yields:
Adding more such layers changes the parameterization but leaves an affine input-output function. Nonlinearities are what allow this composition to escape that family. This observation does not mean that all deep linear optimization problems behave identically: factorization changes the parameter landscape.
A complete XOR construction
Let ReLU(t)=max(0,t), and set:
On the four Boolean corners, the output is exactly XOR. Off the corners, the formula defines an absolute difference: at(1/4,3/4) it is 1/2. Matching a truth table does not specify the desired behavior at all other inputs.
To see the affine obstruction, any affine scalar score s on these corners satisfies s(0,0)+s(1,1)=s(1,0)+s(0,1). If the two XOR-positive scores were at least a threshold and both negative scores were strictly below it, the right sum would be at least twice the threshold while the left sum would be smaller. This contradicts the identity. Adding two nonlinear hidden units removes that obstruction.
Inspect every layer with rational arithmetic
The complete Python 3.12 example uses rational numbers. Rows of each weight matrix correspond to output units. It checks dimensions before multiplication so mismatched shapes cannot silently truncate through zip.
from fractions import Fraction as F
from itertools import product
def layer(x, weights, bias, relu=False):
x=list(x);weights=[list(row) for row in weights];bias=list(bias)
if type(relu) is not bool or not 1<=len(x)<=32 or not 1<=len(weights)==len(bias)<=32:
raise ValueError('bounded nonempty layer dimensions required')
if any(len(row)!=len(x) for row in weights):
raise ValueError('each row must match the input dimension')
values=x+bias+[v for row in weights for v in row]
if any(type(v) not in (int,F) or abs(v)>1000000 for v in values):
raise ValueError('bounded rational values required')
z=[sum((F(w)*a for w,a in zip(row,x)),F(b)) for row,b in zip(weights,bias)]
return [max(F(0),v) for v in z] if relu else z
def xor_network(x, nonlinear=True):
h=layer(x,[[1,-1],[-1,1]],[0,0],relu=nonlinear)
return layer(h,[[1,1]],[0])[0]
if __name__=='__main__':
for x in product((0,1),repeat=2):
print('input:',x,'ReLU output:',xor_network(x),'identity output:',xor_network(x,False))
print('off-corner input (1/4,3/4):',xor_network([F(1,4),F(3,4)]))
print('trainable scalar slots in dense 2-2-1 architecture:',2*2+2+1*2+1)
Actual output:
input: (0, 0) ReLU output: 0 identity output: 0
input: (0, 1) ReLU output: 1 identity output: 0
input: (1, 0) ReLU output: 1 identity output: 0
input: (1, 1) ReLU output: 0 identity output: 0
off-corner input (1/4,3/4): 1/2
trainable scalar slots in dense 2-2-1 architecture: 9
Turning off the ReLU leaves the chosen two hidden differences with opposite signs. The output sums them to zero on every input, as the affine-collapse formula predicts. Our tests check all four corners, an off-corner point, a separate affine composition with nonzero biases, and malformed dimensions.
For a single example, dense evaluation takes O(hd+qh) arithmetic operations. Parameters occupy O(P) storage and the hidden activation O(h). Rational arithmetic is used for exact inspection; its bit costs can grow with numerator and denominator sizes, unlike a fixed-precision operation count. This is a forward evaluator, not a training implementation.
Expressive layers do not settle learning
The construction answers whether these units can represent XOR. It does not answer whether a chosen initialization, loss and optimizer will find this construction, how many observations are needed, or whether the resulting extension beyond the corners is useful. Those are optimization and generalization questions.
Dense layers do not encode spatial locality or sequence order by themselves. Convolution, attention and recurrent designs impose different structures. MLPs can still serve as components inside those systems. Compare models under a fixed evaluation protocol instead of ranking architectures from their names.
Permuting hidden units and applying the same permutation to the output connections leaves the function unchanged. With ReLU, positive rescaling of one unit’s incoming weights and bias can also be undone in its outgoing weight. Parameters are therefore not a unique description of the learned function. Counting parameters is useful for storage and capacity discussions, but is not a direct measure of knowledge.
What did the hidden layer add?
- How many scalar parameter slots does a dense 2→2→1 network have, including biases?
Answer 1: Nine: four input weights, two hidden biases, two output weights and one output bias.
- What does our network return at(1,0) and(1/4,3/4)?
Answer 2: One and one half, respectively, because it computes absolute difference.
- What happens if both hidden ReLUs are replaced by identity functions with the same weights?
Answer 3: The two opposite differences sum to zero for every input.
- Does a zero-error handwritten XOR network demonstrate successful training or generalization?
Answer 4: It demonstrates representability and verifies four outputs. No training took place; off-corner usefulness requires a specified task and evaluation.
From a construction to a trained model
The two sources provide the layer-composition framework; the exact rational construction and checks here are original teaching material. D2L uses row-wise batches, whereas this chapter uses columns. Both conventions are valid when dimensions and transposes remain consistent.
Continue with backpropagation to compute gradients through layers, then universal approximation to examine a broader existence claim. An existence theorem and a successful training experiment provide different kinds of evidence.
Make a prediction, then check
What does the constructed network compute away from Boolean corners?
Learning objectives
- Track layer dimensions and count parameters.
- Prove affine collapse and inspect a nonlinear XOR construction.
Prerequisites & connections
Explore related knowledge →References
- Dive into Deep Learning — 5.1 Multilayer Perceptrons
Aston Zhang; Zachary C. Lipton; Mu Li; Alexander J. Smola · 2023 - Deep Learning — Chapter 6: Deep Feedforward Networks
Ian Goodfellow; Yoshua Bengio; Aaron Courville · 2016
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-06 · Codex single-agent authored technical review: cited primary-source scope, explicit assumptions, original calculations and counterexamples, runnable tests and bilingual review; not independent human or second-agent review.
- Single-agent authored technical review: bounded primary-source locations, assumptions, original derivations, exact/literal references and matching bilingual equations/examples/exercises. Not independent human or second-agent review.
- Four focused CPython3.12.4 tests passed per chapter. Neuron gradients, exact XOR/affine composition, sharp interpolation errors and stable activation/loss derivatives are checked against literal references, analytic identities and finite differences. No external runtime dependencies.
- Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
- Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.
- Final copy review restored the proper name D2L after prose spacing; no equations, examples or exercises changed. Final English article SHA rebound.
Source locations checked:
- Dive into Deep Learning — 5.1 Multilayer Perceptrons · Section5.1.1.2–5.1.1.3 hidden layers and affine collapse; row-batch convention.
- Deep Learning — Chapter 6: Deep Feedforward Networks · Chapter6 opening composition and Section6.4 architecture design pp193–195; no empirical architecture claims adopted.
Related topics