Module contents
Lesson 2 of 22Core 75 min

The perceptron: learning a hyperplane and hitting XOR

Learn the perceptron rule, prove the Novikoff convergence bound, and investigate the representation limit illustrated by XOR.

After this lesson you can

  • Implement the perceptron learning rule and interpret it as subgradient descent on perceptron loss.
  • Prove Novikoff's convergence theorem and calculate the (R/γ)² bound on a concrete dataset.
  • Prove that a single perceptron cannot represent XOR and show how a suitable feature map resolves it.
  • Compare the perceptron and averaged perceptron on nonseparable data.

Before you start

Learning a boundary through corrections

The neuron from the previous lesson can choose between two classes by comparing its logit with zero. Can the line be learned without calculating probabilities? Present an example, check which side it falls on, and if its margin is not correct, rotate and shift the boundary toward it. The perceptron algorithm turns this idea into a precise rule and, under a geometric assumption, bounds the total number of corrections before the data are seen.

Rosenblatt’s work on the perceptron was published in 1958. The convergence proof below is a version of the bound associated with Novikoff, who presented a simplification of earlier proofs in 1962. Historical references appear in the lesson design; here the question is exactly what the argument guarantees, and what it leaves out.

InteractiveCorrect an example
  • Class +1
  • Class −1
  • Current spatial weights
  • Latest spatial correction
The dashed line is the fixed reference separator x1=0x_1=0; points stay on their side so the margin is positive. The ring marks the latest updated point. Arrows represent only the first two coordinates; bounds and bias use the augmented vector (w1,w2,b)(w_1,w_2,b). Ties also trigger updates.
0 / 4 corrections
Margin γ\gamma0.60
Augmented radius R2R^24.20
Bound (R/γ)2(R/\gamma)^211.7
Product w~⋅w~∗\tilde{\vb{w}}\cdot\tilde{\vb{w}}^*0.00 ≥ 0.00
∥w~∥2\|\tilde{\vb{w}}\|^20.00 ≤ 0.00
Current bias0.00
Step through the rule. Bias is included as a constant coordinate: products and norms in the bound are calculated in this augmented space. If you move the data, check that the reference separator remains valid.

Threshold and update rule

The binary perceptron assigns a class based on the sign of w⊤x+b\vb{w}\T\vb{x}+b. Use yi∈{−1,+1}y_i\in\{-1,+1\} and the augmented vectors x~i=(xi,1)\tilde{\vb{x}}_i=(\vb{x}_i,1), w~=(w,b)\tilde{\vb{w}}=(\vb{w},b). The logit is then w~⊤x~i\tilde{\vb{w}}\T\tilde{\vb{x}}_i. Augmentation turns the bias into another coordinate: shifting the boundary is equivalent to changing the last weight. For clarity, use xi\vb{x}_i and w\vb{w} for the augmented vectors in the rest of the proof.

The perceptron learning rule examines examples in some order and starts at w0=0\vb{w}_0=\vb{0}. If yiwt⊤xi≤0y_i\vb{w}_t\T\vb{x}_i\le0, it updates

wt+1=wt+yixi;\vb{w}_{t+1}=\vb{w}_t+y_i\vb{x}_i;

If the product is positive, weights do not change. Here tt counts updates, not examples examined or epochs. A tie triggers an update even if a particular sign convention would assign that label correctly. With a positive constant rate η\eta, the rule adds ηyixi\eta y_i\vb{x}_i; starting from zero, the weights are η\eta times those of the preceding rule for the same sequence, so the signs and the update bound do not change.

Geometrically, the correction adds xi\vb{x}_i for a positive example and subtracts xi\vb{x}_i for a negative one. The examined example’s logit changes by yi∥xi∥2y_i\norm{\vb{x}_i}^2, so its signed margin increases by ∥xi∥2\norm{\vb{x}_i}^2. This does not guarantee that the example is correctly classified in one step or that previous decisions are preserved.

The perceptron loss for one example is ℓ(w)=max⁡(0,−yw⊤x)\ell(\vb{w})=\max(0,-y\vb{w}\T\vb{x}). It is convex, and if the margin is negative, −yx-y\vb{x} is its gradient. At zero margin, −yx-y\vb{x} is one of its subgradients: the update is a subgradient step even at a tie. But the loss is already zero at w=0\vb{w}=0, so each step cannot be claimed to strictly decrease it. Do not confuse it with hinge loss max⁡(0,1−yw⊤x)\max(0,1-y\vb{w}\T\vb{x}), which requires margin one and is used in margin classifiers.

Novikoff’s bound

Proof

Each time you update with an example ii, the margin assumption gives

wt+1⊤w∗=wt⊤w∗+yixi⊤w∗≥wt⊤w∗+γ.\vb{w}_{t+1}\T\vb{w}_*=\vb{w}_t\T\vb{w}_*+y_i\vb{x}_i\T\vb{w}_*\ge\vb{w}_t\T\vb{w}_*+\gamma.

By induction, wt⊤w∗≥tγ\vb{w}_t\T\vb{w}_*\ge t\gamma. On the other hand, since you update only when yiwt⊤xi≤0y_i\vb{w}_t\T\vb{x}_i\le0,

∥wt+1∥2=∥wt∥2+2yiwt⊤xi+∥xi∥2≤∥wt∥2+R2.\norm{\vb{w}_{t+1}}^2=\norm{\vb{w}_t}^2+2y_i\vb{w}_t\T\vb{x}_i+\norm{\vb{x}_i}^2\le\norm{\vb{w}_t}^2+R^2.

Another induction gives ∥wt∥2≤tR2\norm{\vb{w}_t}^2\le tR^2. By Cauchy-Schwarz and ∥w∗∥=1\norm{\vb{w}_*}=1, tγ≤wt⊤w∗≤∥wt∥≤tRt\gamma\le\vb{w}_t\T\vb{w}_*\le\norm{\vb{w}_t}\le\sqrt t R. For t>0t>0, dividing by t\sqrt t and squaring gives t≤(R/γ)2t\le(R/\gamma)^2; for t=0t=0 the bound is immediate.

∎

If all examples are repeatedly traversed, there will be a complete epoch without updates: otherwise infinitely many would occur, contradicting the bound. At the end of an unchanged epoch, all margins are positive. Dimension does not appear explicitly in the bound, but can influence RR and γ\gamma. Nor is maximum separation guaranteed: any obtained separator suffices. The perceptron convergence theorem requires separability with positive margin; it does not apply if the assumed separator does not exist.

InteractiveMargin and number of corrections
Vertical axis: log₁₀ of updates or bound
Horizontal axis: log₁₀ of margin
  • Observed updates
  • Bound (R/γ)²
  • Selected margin

Both axes show base-10 logarithms. Points are actual runs on the same dataset: tangential coordinates are generated with seed 42 and retained as γ moves. Each input is xᵢ = yᵢ(γ, tᵢ), with alternating labels and tᵢ between −1 and 1, including both endpoints. The unit separator (1, 0) has margin γ and R = √(1 + γ²). Weights start at zero and ties also trigger updates. The bound increases as margin decreases, but the observed count can vary with order and data.

−1.00
Margin γ\gamma0.1000
Radius RR1.0050
Updates8
Bound (R/γ)2(R/\gamma)^2101.00
Passes, including the final one2
Change the margin of a reproducible dataset and compare actual updates with the bound. The error curve also depends on order and need not grow monotonically.

This figure uses a homogeneous model without bias: points are yi(γ,ti)y_i(\gamma,t_i), the unit separator is (1,0)(1,0) and the margin is γ\gamma. The lab below explicitly adds a constant coordinate and calculates its own bound in that different space.

In augmented space RR includes the constant coordinate. Changing that coordinate’s scale changes the geometry of parameter space and the bound: you cannot take RR from the original space and γ\gamma from the augmented one. The separator used to calculate γ\gamma must have unit norm in that same space. An upper bound does not predict the exact number of corrections or claim that every order needs the same number.

Nonseparable data and XOR

Without separability, the proof offers no finite limit; when an incompatible dataset is traversed indefinitely, the algorithm can keep updating. A finite run needs an epoch budget and a rule for choosing what to return. The pocket keeps the best iterate seen according to a fixed training criterion. Here we use the number of nonpositive margins and keep the first in case of a tie. A zero margin is counted for both classes: this metric is not exactly the number of errors under a classification rule that assigns ties to one class. The averaged perceptron returns the average iterate along the sequence; we also include steps without updates. This can stabilize a trajectory, but does not guarantee better generalization for every sample or replace separate evaluation.

The XOR limitation is an impossibility of representation, not just an optimizer failure. Take inputs (0,0),(1,0),(0,1),(1,1)(0,0),(1,0),(0,1),(1,1) and label them positive exactly when their coordinates differ. A threshold with positive class if z>0z>0 and negative if z≤0z\le0 would require

b≤0,w1+b>0,w2+b>0,w1+w2+b≤0.b\le0,\quad w_1+b>0,\quad w_2+b>0,\quad w_1+w_2+b\le0.

Adding the two middle inequalities gives w1+w2+2b>0w_1+w_2+2b>0, while adding the first and last gives w1+w2+2b≤0w_1+w_2+2b\le0: a contradiction. Both classes have the same midpoint (1/2,1/2)(1/2,1/2), a geometric reading of the same obstruction. The result does not depend on which algorithm fits the line.

Minsky and Papert’s book Perceptrons, published in 1969, mathematically studied limits of perceptron families. The result above concerns an affine threshold on these two inputs, not a proof that all multilayer networks cannot represent XOR. It raises the question of how to construct or learn representations in which linear separation is possible.

InteractiveXOR and a new feature
  • XOR = 1
  • XOR = 0

Predict 1 if z=w1x1+w2x2+b>0z=w_1x_1+w_2x_2+b>0 and 0 if z≤0z\le 0. To classify correctly, all four inequalities must hold:

(0,0): b≤0(0,0):\ b\le 0
Score −0.5: satisfied
(1,0): w1+b>0(1,0):\ w_1+b>0
Score 0.5: satisfied
(0,1): w2+b>0(0,1):\ w_2+b>0
Score 0.5: satisfied
(1,1): w1+w2+b≤0(1,1):\ w_1+w_2+b\le 0
Score 1.5: not satisfied

Adding the conditions for XOR = 1 gives w1+w2+2b>0w_1+w_2+2b>0. Those for XOR = 0 require the same sum ≤0\le 0. Both cannot hold at once.

1.0
1.0
-0.5
Correct with line3 / 4
Try to separate the four inputs with a linear boundary. Then add the product feature: separation occurs in transformed space, not by a line in the original plane.

A fixed map ϕ(x1,x2)=(x1,x2,x1x2)\phi(x_1,x_2)=(x_1,x_2,x_1x_2) does permit separation: x1+x2−2x1x2−0.5x_1+x_2-2x_1x_2-0.5 equals 0.50.5 on the two positive inputs and −0.5-0.5 on the two negatives. Hidden layers offer another route: learning features from data. A fixed and a learned map are different interventions, though both can make the represented problem linearly separable.

Lab: rules and bound in NumPy

The following code counts updates, not classification errors under an arbitrary tie convention. Input matrices include a column of ones. When comparing with scikit-learn, its intercept is disabled because the constant column already represents it; shuffling and tolerance-based stopping are also disabled so that comparing the traversal makes sense.

[ ]Perceptron, averaging and pocketBrowser
import numpy as np

def train_perceptron(X, y, epochs):
    w = np.zeros(X.shape[1])
    total = np.zeros_like(w)
    seen = 0
    best = w.copy()
    best_errors = np.sum(y * (X @ best) <= 0)
    counts = []
    for _ in range(epochs):
        updates = 0
        for x, label in zip(X, y):
            if label * (w @ x) <= 0:
                w += label * x
                updates += 1
                errors = np.sum(y * (X @ w) <= 0)
                if errors < best_errors:
                    best, best_errors = w.copy(), errors
            total += w
            seen += 1
        counts.append(updates)
    return w, total / seen, best, np.array(counts)
[ ]Verify the bound across many seedsBrowser
def separable(seed, margin=0.25, n=40):
    rng = np.random.default_rng(seed)
    y = rng.choice([-1., 1.], size=n)
    x1 = y * margin
    x2 = rng.uniform(-1, 1, size=n)
    X = np.column_stack([x1, x2, np.ones(n)])
    return X, y

updates = []
ratios = []
for seed in range(200):
    Xs, ys = separable(seed)
    ws = np.zeros(Xs.shape[1])
    count = 0
    for epoch in range(100):
        changes = 0
        for x, label in zip(Xs, ys):
            if label * (ws @ x) <= 0:
                ws += label * x
                changes += 1
        count += changes
        if changes == 0:
            break
    assert changes == 0
    bound = (np.linalg.norm(Xs, axis=1).max() / 0.25) ** 2
    updates.append(count)
    ratios.append(count / bound)
assert max(ratios) <= 1 + 1e-12
print('actualizaciones mín/máx', min(updates), max(updates))
print('mayor proporción de la cota', round(max(ratios), 4))

The augmented separator w∗=(1,0,0)\vb{w}_*=(1,0,0) has unit norm and margin exactly 0.250.25; the last component of each example still counts toward RR. This simulation checks the algorithm on a finite family, but does not prove the theorem or justify extrapolating a universal error curve.

[ ]Compare with scikit-learnBrowser
from sklearn.linear_model import Perceptron

X, y = separable(7)
w, avg, pocket, counts = train_perceptron(X, y, 30)
sk = Perceptron(fit_intercept=False, shuffle=False, max_iter=30, tol=None, eta0=1.0)
sk.fit(X, y)
print('pesos propios', np.round(w, 4))
print('pesos sklearn', np.round(sk.coef_[0], 4))
print('actualizaciones', counts.sum(), 'márgenes positivos', np.all(y * (X @ w) > 0))
[ ]An incompatible datasetBrowser
Xxor = np.array([[0., 0., 1.], [1., 0., 1.], [0., 1., 1.], [1., 1., 1.]])
yxor = np.array([-1., 1., 1., -1.])
last, average, pocket, counts = train_perceptron(Xxor, yxor, 40)
def errors(w):
    return int(np.sum(yxor * (Xxor @ w) <= 0))
print('actualizaciones por últimas épocas', counts[-5:])
print('márgenes no positivos último/promedio/bolsillo', errors(last), errors(average), errors(pocket))
sk_xor = Perceptron(fit_intercept=False, shuffle=False, max_iter=40, tol=None, eta0=1.0)
sk_xor.fit(Xxor, yxor)
print('pesos sklearn XOR', sk_xor.coef_[0], 'márgenes no positivos', errors(sk_xor.coef_[0]))
Xex = np.array([[1., 0., 1.], [1., 1., 1.], [-1., 0., 1.], [-1., -1., 1.]])
yex = np.array([1., 1., -1., -1.])
reference = np.array([1., 0., 0.])
R = np.linalg.norm(Xex, axis=1).max()
gamma = (yex * (Xex @ reference)).min()
print('ejercicio: R, margen, cota', R, gamma, (R / gamma) ** 2)

Results for this last dataset count nonpositive training margins for one sequence. They do not prove that pocket or averaging generalizes better. To study generalization, split examples before choosing the variant and evaluate once on data not used for that choice.

Exercises

ProofTwo growth rates
Prove: Prove that the number of updates is bounded by (R/γ)² under the theorem's assumptions.
0
The reference separator is unit length, has margin at least γ > 0, and each augmented example has norm at most R.

Step 1 of 3. How much does the product with the separator increase?

ProofThe XOR contradiction
Prove: No affine threshold that assigns the positive class to a strictly positive logit represents XOR.
0
Positive inputs are (1,0) and (0,1); negative inputs are (0,0) and (1,1).

Step 1 of 3. What do the positive inputs require?

NumericA concrete bound
In augmented space consider the four examples (1,0,1), (1,1,1), (-1,0,1), (-1,-1,1), with labels +1,+1,-1,-1. For the unit separator (1,0,0), calculate (R/γ)².
QuizWhat does averaging guarantee?
On a nonseparable dataset, what can you say about the averaged perceptron compared with the last iterate?
CodeEpoch after epoch
Implement perceptron_train(X, y, epochs). X already includes the bias column and y contains −1 or +1. Initialize weights to zero, traverse examples in order and update when the margin is nonpositive. Return the weight vector and a list of updates for each epoch.
import numpy as np

def perceptron_train(X, y, epochs):
  pass
Shift+Enter to run
Key idea

A correction adds yxy\vb{x} in augmented space. If a unit separator with positive margin exists, progress toward it grows linearly while the norm grows at most with the square root of the number of corrections: this yields the bound. XOR shows the limit of the boundary family, and an additional feature shows one way to change that family.