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.
Threshold and update rule
The binary perceptron assigns a class based on the sign of . Use and the augmented vectors , . The logit is then . Augmentation turns the bias into another coordinate: shifting the boundary is equivalent to changing the last weight. For clarity, use and for the augmented vectors in the rest of the proof.
The perceptron learning rule examines examples in some order and starts at . If , it updates
If the product is positive, weights do not change. Here 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 , the rule adds ; starting from zero, the weights are times those of the preceding rule for the same sequence, so the signs and the update bound do not change.
Geometrically, the correction adds for a positive example and subtracts for a negative one. The examined example’s logit changes by , so its signed margin increases by . 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 . It is convex, and if the margin is negative, is its gradient. At zero margin, is one of its subgradients: the update is a subgradient step even at a tie. But the loss is already zero at , so each step cannot be claimed to strictly decrease it. Do not confuse it with hinge loss , which requires margin one and is used in margin classifiers.
Novikoff’s bound
Proof
Each time you update with an example , the margin assumption gives
By induction, . On the other hand, since you update only when ,
Another induction gives . By Cauchy-Schwarz and , . For , dividing by and squaring gives ; for 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 and . 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.
This figure uses a homogeneous model without bias: points are , the unit separator is and the margin is . The lab below explicitly adds a constant coordinate and calculates its own bound in that different space.
In augmented space includes the constant coordinate. Changing that coordinate’s scale changes the geometry of parameter space and the bound: you cannot take from the original space and from the augmented one. The separator used to calculate 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 and label them positive exactly when their coordinates differ. A threshold with positive class if and negative if would require
Adding the two middle inequalities gives , while adding the first and last gives : a contradiction. Both classes have the same midpoint , 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.
A fixed map does permit separation: equals on the two positive inputs and 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.
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)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 has unit norm and margin exactly ; the last component of each example still counts toward . This simulation checks the algorithm on a finite family, but does not prove the theorem or justify extrapolating a universal error curve.
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))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
Step 1 of 3. How much does the product with the separator increase?
Step 1 of 3. What do the positive inputs require?
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):
passA correction adds 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.