Perceptron
感知机算法
Derive the signed update and finite update bound, account for the augmented bias, and prove why raw XOR features cannot be separated.
perceptronMove the boundary after an unhelpful prediction
Start with two invented observations: the number −1 belongs to class −1, and the number 1 belongs to class +1. A linear score should be negative on the first and positive on the second. We can find suitable parameters by correcting one observation at a time. This is the modern binary perceptron learning rule.
Initialize . Both observations lie on the current boundary. Seeing the first point changes the parameters to . The second point still has score zero, so another update gives . The resulting scores are −2 and +2. The update uses the labeled observation itself to move the boundary; it does not differentiate the threshold decision.
That small example raises a useful question: will such corrections eventually stop, or can fixing one point keep breaking another? The answer depends on whether the chosen features allow a strict linear separation. The convergence theorem explains both the guarantee and its limits.
Keep the label, bias and margin conventions explicit
Let and . Store the bias in an extra coordinate:
Our prediction rule returns +1 for a score at least zero and −1 otherwise. Training is stricter: an example with triggers
A zero score therefore triggers an update even if the prediction tie rule happened to name the correct class. Throughout the proof, count updates, including boundary events. Ordinary prediction mistakes are a subset of these events. Labels encoded as 0 and 1 must first be changed to −1 and +1; using label zero directly would produce no correction at all. Cornell’s perceptron notes develop the bias transformation and signed-label rule.
For the selected example, the signed score increases by , since . This is progress on that example, though a very negative score may require further updates. Scores of other examples can improve or deteriorate.
Here are the precise assumptions for a finite update bound. Start from . Suppose every example that can be presented satisfies , and there is a unit vector with a positive separating margin:
Each update makes at least progress along . Its effect on the squared parameter norm is bounded because the current signed score is nonpositive:
After updates, and . Cauchy–Schwarz then gives
The final division applies when ; the zero-update case already satisfies the bound. A finite strictly separable dataset has some positive minimum margin. Repeated full scans must eventually contain no updates, because infinitely many unsuccessful scans would contradict this bound. Cornell proves the normalized version; the derivation above retains the input radius explicitly.
The bias matters here. Both and refer to augmented space. For an affine separator , normalization divides by . Distance to its hyperplane in the original feature space instead divides by when . Mixing those two quantities gives an invalid bound. In the opening example, , and : the upper bound is two, exactly the observed number of updates.
Use exact small inputs and report the stopping state
The complete standard-library program uses integers or Fraction coordinates, a zero initialization, unit update steps and a fixed training order. Fractions make boundary comparisons exact for these small examples. A full scan is an epoch. The program returns the parameters, total update count, completed epochs and whether every training example has a strictly positive signed score. Reaching the epoch cap without separation is a reported outcome, not a proof of impossibility.
from fractions import Fraction as F
def coordinate(value):
if type(value) is not int and not isinstance(value,F):
raise ValueError("integer or Fraction coordinates required")
return F(value)
def perceptron(points,labels,max_epochs=100):
x = [tuple(coordinate(v) for v in row) for row in points]
y = list(labels)
if not x or len(x) != len(y) or not x[0]:
raise ValueError("matching nonempty data required")
if any(len(row) != len(x[0]) for row in x):
raise ValueError("rectangular features required")
if any(type(label) is not int or label not in (-1,1) for label in y):
raise ValueError("labels must be integers -1 or +1")
if type(max_epochs) is not int or max_epochs < 1:
raise ValueError("positive integer epoch cap required")
a = [(F(1),)+row for row in x]
theta = [F(0)]*len(a[0])
updates = 0
for epoch in range(1,max_epochs+1):
changed = 0
for row,label in zip(a,y):
if label*sum(w*v for w,v in zip(theta,row)) <= 0:
theta = [w+label*v for w,v in zip(theta,row)]
changed += 1
updates += changed
if changed == 0:
return theta,updates,epoch,True
# The last update may already have separated all points: check the final state.
separated = all(label*sum(w*v for w,v in zip(theta,row)) > 0
for row,label in zip(a,y))
return theta,updates,max_epochs,separated
def predict(theta,point):
# theta is the parameter vector returned by perceptron.
row = (F(1),)+tuple(coordinate(v) for v in point)
if len(row) != len(theta):
raise ValueError("query dimension must match the fitted model")
return 1 if sum(w*v for w,v in zip(theta,row)) >= 0 else -1
square = [(0,0),(0,1),(1,0),(1,1)]
theta,updates,epochs,separated = perceptron(square,[-1,-1,-1,1])
assert theta == [-4,3,2] and updates == 18 and separated
assert [predict(theta,row) for row in square] == [-1,-1,-1,1]
# Exact arithmetic exposes this particular XOR cycle.
result = perceptron(square,[-1,1,1,-1],max_epochs=20)
assert result == ([F(0)]*3,80,20,False)
assert perceptron([(-1,),(1,)],[-1,1])[1] == 2
The first parameter is the bias. Prediction deliberately assigns a zero score to +1, while training updates on zero regardless of label. The final verification after the cap avoids overlooking a separator obtained by the very last update. The code validates dimensions and label encoding; it rejects floating-point coordinates so a rounded boundary is not silently treated as exact.
For the AND truth table, the returned parameters are after 18 updates. A separate separating certificate is . Its four signed scores are . Normalizing gives and , so 51 is a valid bound. The program does not need to know this certificate while training.
With examples, original features and scans, computation costs arithmetic operations. Copied training data uses storage; a prediction costs . Fraction bit costs also depend on numerator and denominator size. The update bound is not itself the number of dot products: correctly classified points still have to be inspected.
XOR is a representation problem
For XOR, give and negative labels, and and positive labels. Strict separation would require the sum of the two positive scores to be positive and the sum of the two negative scores to be negative. Both sums equal . They cannot have opposite signs. No adjustment to these three affine parameters can solve that contradiction.
In the code’s particular order, XOR produces four updates and returns to zero parameters every epoch. Other nonseparable datasets or orders need not have this same cycle. An iteration limit merely stops computation; neither a large update count nor the failure of a finite parameter search proves nonseparability. The algebra above supplies that proof for XOR.
Additional nonlinear features or hidden units change the family of boundaries that can be represented; activation functions gives a hand-constructed XOR example. More passes over unchanged raw XOR features do not make this linear model richer. Noise and conflicting labels can also prevent strict separation.
Even when convergence holds, the returned separator need not have the largest margin, be unique, or generalize well. Ordering and feature scaling affect the update trajectory. The theorem assumes zero initialization and the stated update rule. A fixed positive learning rate can be incorporated by scaling the proof, but arbitrary varying step schedules or modifications require their own analysis.
Check a correction and a guarantee
- Starting from , what update follows the example ? Answer: add , obtaining . Adding without its label would move the slope in the wrong direction.
- A positive example has score zero and the prediction rule returns +1. Why update it? Answer: training requires a strictly positive signed score. The update count includes boundary events, even when the prediction tie rule happened to be correct.
- For the AND certificate , compute the augmented-space bound. Answer: , the smallest unnormalized signed score is 1, and . Thus .
- Does failing to fit XOR after 20 epochs prove impossibility? Answer: the run alone does not. The proof is that its positive-score sum and negative-score sum are the identical expression , so they cannot both meet strict separation requirements.
A historical model and a modern learning rule
Rosenblatt’s 1958 paper discusses a wider system of sensory, association and response units, with learning through changes in connection effects. The compact linear algorithm taught here is a modern mathematical formulation, not a reconstruction of the whole proposed machine. Its biological motivation does not make its units faithful models of real neurons.
The perceptron remains a useful entry into online learning because every correction and every assumption can be inspected. Margin-based classifiers ask for additional properties of a separator; probabilistic models such as logistic regression fit a conditional probability rather than returning only a threshold decision. Compare those objectives on the same representation and evaluation split before deciding which behavior a task needs.
Make a prediction, then check
A positive example has zero score and prediction+1. Does this article’s training rule still update?
Learning objectives
- Derive the biased perceptron update and its finite update bound in augmented space.
- Distinguish training failure, representation limits and generalization using separator certificates and XOR.
Prerequisites & connections
Explore related knowledge →References
- The Perceptron: A Probabilistic Model for Information Storage and Organization in the Brain
Frank Rosenblatt · 1958 - Cornell CS4780 Fall2018 — Lecture3: The Perceptron
Cornell University · 2018
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-05 · Codex technical check: source locations, independent numerical verification and full bilingual rereading; some drafts by an agent reviewed by the parent; no independent human peer review.
- Parent executed336 Boolean-label/order fits with independent integer certificates; all strictly separate within the augmented bound. Also checked final-cap verification, bias on zero features, XOR cycles and input contracts.
- Parent compared complete bilingual derivations and exercises; changed the summary from finite mistake bound to finite update bound to match boundary-inclusive counting.
- The parent executed all19 independent learning-theory/neural tests. Structure checks compare bilingual anchors,display equations,code and sources; parent reread four answers and arguments. Historical articles make no code-execution claim.
Source locations checked:
- The Perceptron: A Probabilistic Model for Information Storage and Organization in the Brain · Writing agent read original scan PDF1–2,4–5,17–18 (printed386–387,389–390,402–403): aims, S/A/R organization, bivalent reinforcement. Compact modern algorithm not claimed to reconstruct the entire model.
- Cornell CS4780 Fall2018 — Lecture3: The Perceptron · Agent and parent read assumptions, bias augmentation and full convergence proof, lines9–51. Cross term must be nonpositive, not strictly negative; own proof retains augmented radiusR, unit separator and boundary updates. Historical winter claim not adopted.
Related topics