In P4.1 you set the weights of a perceptron for AND and OR by hand. That worked because the pictures were tiny. Real problems have thousands of inputs, and nobody can set those weights by hand.
So can the perceptron find its own weights? In the late 1950s Frank Rosenblatt showed that it can, with a rule so simple that it fits on one line: look at an example, and if the perceptron is wrong, nudge the weights toward the right answer. This lesson explains the rule, proves it works when it can, and then meets the four-point problem on which it fails for ever.
Learn from mistakes
Remember the perceptron from P4.1. It computes a score . In P4.1 the step gave when . For learning, this lesson uses the labels and and counts a score of exactly as undecided (the tie convention below), so the answer is when and when . The line is its decision boundary, and points at the side that gets .
Now suppose you have training examples with known labels , each or , and you start with some weights. Go through the examples one at a time:
- If the perceptron answers correctly, do nothing.
- If it answers wrongly, change and so that this example is a little closer to being right.
That is the whole idea. The rest of the lesson makes “a little closer” exact.
The rule
For one example with and a learning rate (the step size, as in P1.F3):
The product is positive when the answer is right and negative when it is wrong, so “” means “wrong”. A score of exactly is undecided, so the rule treats it as wrong for either label. This is a convention, and it matters: from the start , every score is exactly , and the rule could never begin without it. scikit-learn’s Perceptron uses the same convention.
Read the update in words. For a positive example you add a copy of to , so turns toward the point. For a negative example you subtract it, so turns away. The bias is the weight of an input that is always , so it moves by .
The 0/1 form. Many books use targets , an output , and the update , . It is the same rule. The error is when the answer is right, when the target is and the output , and in the opposite case. On a mistake, equals (with ), so the two updates are identical. The two forms differ only on ties, where exactly: the step function must give a tie one value, while the rule above counts a tie as wrong for both labels. This lesson uses the form and the tie convention above throughout.
One update, with numbers
Let , and , and take the example with . The score is , so : a mistake. The update gives and . The new score for this example is . It was and is now , so this example is now right.
Why the update moves the line the right way
After the update on a mistake, the score of the same example changes by
The new score is , and subtracting the old score leaves . The factor is positive, so for a positive example the score goes up and for a negative example it goes down. That is always the direction that makes this example more correct. In the example above it rose from to , a change of .
Geometrically, the boundary is the set of points with score . Raising the score at pulls the boundary toward the point , or pushes it past the point, depending on how far away it was.
The last sentence is the catch. The rule only looks at one example, and the nudge that fixes it can break another. Whether this process ends up somewhere good is a real question, and a theorem answers it below.
A full run by hand: learning OR
Take the four points of OR, in this fixed order, with labels or : , , , . Start from , , with . One pass through the four points is an epoch. Here is every step, with the score each example gets before the update.
Epoch 1.
- , : score , a tie, so a mistake. Subtract: , .
- , : score , a mistake. Add: , .
- , : score , a mistake. Add: , .
- , : score , correct.
Three mistakes. Now , , which says “output when ”. That gives for all four points, so is wrong.
Epoch 2. has score but : a mistake, so . The other three points have scores , , , all correct. One mistake. Now , .
Epoch 3. has score : a mistake, . has score : a mistake, so , . The last two are correct. Two mistakes.
Epoch 4. has score : a mistake, . has score , correct. has score : a mistake, so , . is correct. Two mistakes.
Epoch 5. has score : a mistake, . The other three have scores , , . One mistake. Now , .
Epoch 6. The scores are , , , with labels , , , . All correct. Zero mistakes, so the rule stops.
The mistakes per epoch were : nine updates in all. The result is , : the perceptron outputs when . That is OR, found without anyone setting a weight. Running the code in the Code tab below, and the widget in the next section, give the same numbers. AND from the same start takes more work: epochs and updates, ending at , .
See it: the rule on five data sets
Try it.
- Pick OR, press Step three times, and compare with the first epoch of the hand run above. Then press Reset and Epoch five times to see , .
- Pick the random separable set and press Epoch. It needs 3 epochs, with , and mistakes.
- Pick XOR and press Epoch a few times. Every epoch has mistakes, and the status tells you the weights have come back to where they were.
- Pick Noisy (the separable set with two labels flipped) and keep pressing Epoch. The mistakes bounce around and never settle at .
- Pick AND and set the learning rate to , then to . The mistakes per epoch stay the same. Press “Start at w = (1, −1), b = 0.5”. With the run stops after 7 epochs. Set , press Reset and then Epoch repeatedly: it takes 20.
Epochs, stopping, the learning rate and the start
Epochs and stopping. The rule keeps passing over the data. It stops when one complete epoch has no mistakes: then every example is right and no update is ever triggered again, so nothing changes. Examples are usually shuffled between epochs in real code. This lesson keeps a fixed order so every run can be reproduced.
The learning rate does very little here, from a zero start. The mistakes on the first epoch depend only on signs. Start at , , and every update adds to . After any number of updates, and are times what they would be with , so every score is times larger. Multiplying scores by a positive number changes no signs and no ties, so the same examples are mistakes, and the boundary is exactly the same line. Running AND with gives , and the same mistakes per epoch as . So with the perceptron rule from zero, is as good as any value, and you can pick it.
The starting weights matter. The argument breaks when the start is not zero, because the starting weights do not scale with . Starting AND at , , the rule with stops after 7 epochs, and with it takes 20. A small step now fights a start that was not chosen for this data. Both runs still stop. (The theorem below is stated for a zero start. The same proof gives a bound for any start, with an extra term for how far the start is from a solution.)
Linear separability and the convergence theorem
Two classes are linearly separable if some line (in more dimensions, some plane or hyperplane) has all the points strictly on one side and all the points strictly on the other: there are and with for every example. AND and OR are separable. XOR, below, is not.
Rosenblatt proved convergence in the early 1960s. The clean bound below is Novikoff’s (1962).
Here is the input with the extra . The bound depends on how hard the data is (a small margin means a big bound) and not directly on how many examples there are or how many features (the features enter only through and ).
For OR: (the point ) and the best has , so the bound is . The hand run needed updates. For AND the bound is and the run needed . The bound is a safety guarantee, and real runs are usually far below it.
What the theorem does not promise.
- Which line. Any separating line may come out. The rule stops as soon as the data is separated, with no preference for the middle of the gap. A support vector machine (P3.B6) chooses the widest street, and the perceptron does not try to.
- Anything about data that is not separable. The theorem needs a separating to exist. If it does not, the bound has no content, and the rule does something else, as the next sections show.
- Speed. At most updates can be a very large number when is small.
Go deeper Proof of the bound
Take (a different only rescales everything below, from a zero start). Write for the weights, bias included, after updates, with . At update the example was a mistake, so , and .
It aligns with . . After updates, .
It grows slowly. , because the middle term is not positive on a mistake. So .
Put them together. Since has length , . Divide by : , so .
The two facts pull against each other: the weights must grow at least in step with the number of updates in the direction of , but their length can grow only like the square root. That squeeze can only hold for a limited number of updates. The “middle term is not positive” step is where a mistake is used, and the “” step is where separability is used.
The here is measured with the bias counted as an input, so it is related to, but not identical to, the street width of P3.B6.
The XOR problem
XOR (“exclusive or”) is when exactly one of the two inputs is : the points and have label , and and have label . Draw them on the unit square: the two points sit on one diagonal, the two points on the other.
No line can separate them. Suppose and did. Each point gives one inequality , which simplifies to:
Add the two inequalities: , so . The first one says , so . The last line says . Contradiction, so no such and exist.
What the rule does. The theorem needs a separating line, so it does not apply. From the zero start and the fixed order, the rule on XOR does this in every epoch:
- , : tie, mistake. , .
- , : score , mistake. , .
- , : score , mistake. , .
- , : score , mistake. , .
All four are mistakes, and the weights are back at , . The next epoch is the same, and so on for ever: a cycle of length one epoch. Press Epoch in the widget on XOR and the status says exactly this. In general a run on non-separable data does not have to return to the same weights so neatly. On the noisy set the mistakes per epoch go and never reach .
Go deeper Why a run on non-separable data cannot run away
On any finite data set the weights are known to stay bounded (the perceptron cycling theorem, Block and Levin, 1970), so the run cannot run away. With whole-number data, and a fixed order, bounded whole-number weights have only finitely many values, so the run must eventually return to weights it has had before and then repeat for ever.
When the data is not separable: practical fixes
Real data is rarely perfectly separable, and a mislabelled example is enough to ruin it. A plain perceptron on such data keeps moving, and the weights it has when you stop it can be much worse than weights it had earlier. Two cheap fixes are common:
- The pocket algorithm (Gallant, 1990): run the rule as usual, but keep “in your pocket” the best weights seen so far, and return those. The “ratchet” version, used in the cell below, judges “best” by how many training examples the weights get right.
- Averaging (the averaged or voted perceptron, Freund and Schapire, 1999): return the average of the weights over all steps. Averaging damps the jumps from the last few mistakes.
Here is a quick test on the noisy set of the widget (14 points, 2 labels flipped), over 50 epochs. The code runs in your browser.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
The output on the machine used for this lesson:
epoch 49: plain 12/14
epoch 50: plain 8/14
pocket : 13 / 14
average: 12 / 14
The plain rule’s weights after epoch 50 get only 8 of 14 right, though it had 12 of 14 a moment earlier. The pocket keeps 13 of 14. Checking every line through two of the points, each nudged slightly both ways, finds no line above 13 of 14, so the pocket’s 13 is as good as any line found. Averaging gives 12 of 14. These numbers are for this one data set and order. They show the idea, and they do not rank the methods in general.
The rule is stochastic gradient descent
Here is the link to P1.F3. For one example, define the perceptron loss
If the example is right, and the loss is . If it is wrong, the loss is , which grows the further the score is on the wrong side. For a wrong example the loss equals , so its gradient is and . A gradient-descent step subtracts times the gradient:
That is the perceptron rule. For a correct example the gradient is and nothing moves. So the rule is stochastic gradient descent (one example at a time) on this loss. There is one subtlety. At a score of exactly the loss has a corner and no single gradient, and the convention “a tie is a mistake” picks one of the allowed directions, called a subgradient. Note that , already has loss on every example. The rule leaves it only because the tie rule picks the direction at the corner. So this is SGD with a particular subgradient choice, not a search for the minimum of a loss with a unique answer.
How does this loss compare with the ones you know, as a function of ?
| perceptron | hinge (P3.B6) | logistic (P3.A7) | |
|---|---|---|---|
The hinge loss is the perceptron loss shifted by one: it still charges for correct points that are inside the margin (). That is how the SVM gets its street. The logistic loss (written for , where P3.A7 uses labels) is smooth and never exactly zero. The perceptron loss is exactly zero for every correct example, so once an example is right it is ignored, however close to the line it sits. That is why the rule stops when the data is separated, and also why it picks no particular line. P4.6 covers the losses used for neural networks.
History: the book and the winter
Rosenblatt introduced the perceptron in the late 1950s, at the Cornell Aeronautical Laboratory, and had it built as a machine for recognising simple images. The learning rule and early results drew wide attention and ambitious claims.
In 1969 Marvin Minsky and Seymour Papert published the book Perceptrons (MIT Press). It was a careful mathematical study of what single-layer perceptrons can and cannot compute, and of how many inputs each unit needs to see. XOR, and its many-input version parity, were among the examples of things such a perceptron cannot do. The proofs are about single-layer perceptrons. They are not proofs that networks with hidden layers are weak.
In the 1970s funding for neural-network research became hard to find, and this is often called part of the first AI winter, a period of reduced funding and interest in artificial intelligence (the name came later, in the 1980s). Historians disagree about how much the book caused the funding decline: AI as a whole had over-promised, and funders cut back in several countries, including after the 1973 Lighthill report in the UK. What is clear is that the book’s message was often heard as “neural nets do not work,” which is more than its theorems say.
The way out was already visible. A network with a hidden layer can compute XOR (next section). What was missing was a good way to train the hidden weights. The perceptron rule needs a known correct answer for every unit, and a hidden unit has none. The idea that solves this, backpropagation, had been described by others before (for example Linnainmaa, 1970, and Werbos, 1974), and it became widely known with a 1986 paper by Rumelhart, Hinton and Williams. P4.7 and P4.8 teach it.
The way out
There are two standard ways to separate XOR with perceptrons.
1. Add a feature. Give the perceptron a third input, the product . The four points become , , and , and the score is , , , on them: exactly the labels. A plane separates them. The perceptron rule itself, run on the three inputs from zero, finds a separator: it stops after 12 epochs at , . Adding such features by hand is the idea of polynomial features (P3.A3), and the kernel trick (P3.B7) does it without writing the features out. The weakness is that someone must choose the feature.
2. Add a hidden layer. Use three perceptrons. The first computes OR (weights , bias ), the second computes NAND, “not both” (weights , bias ). The third perceptron takes those two outputs and computes AND (weights , bias ). On the four inputs, the first two give , , , , and the AND of each pair is : XOR. The hidden layer bends the plane: in the plane of the two hidden outputs, the classes are separable. P4.3 shows this with a widget and trains such a network, so the network finds the weights itself.
Intuition
Think of a teacher who looks at one answer at a time and says nothing when it is right. When it is wrong, the teacher pushes the boundary a step toward the correct side. Each push fixes one example and may disturb others. When the classes are separable, the pushes eventually stop disturbing anything. When they are not, the teacher keeps pushing for ever.
The analogy breaks in one place: the teacher never says how wrong an answer was. The update uses only the example and its label, and a correct answer that sits almost on the line gets no push at all.
Math
Rule: if then and .
Score change on that example: .
Loss: , with on a mistake and otherwise. So the rule is SGD with step .
Convergence: with and a unit with , the number of updates is at most .
Code
The function perceptron is in the cell right below these tabs: it loops over the examples, applies if yi * (w @ xi + b) <= 0 to find a mistake, updates w and b, and stops after an epoch with no mistakes.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
Try changing the XOR labels to AND’s, or add a third column to X and see XOR become learnable.
Common mistakes
Quiz
Check your understanding
A perceptron has w = (1, 0), b = 0 and learning rate 1. It sees x = (0, 2) with label +1. Use this lesson’s rule, where a score of exactly 0 counts as a mistake. What are w and b afterwards?
The score is 1·0 + 0·2 + 0 = 0, and the rule counts a score of exactly 0 as a mistake. For a positive example it adds x to w and 1 to b, which gives (1, 2) and 1. Leaving the weights alone would be right only if ties were counted as correct. Subtracting x is the update for a negative example. Leaving b unchanged forgets that the bias is also updated.
You run the perceptron rule on a separable data set from w = 0 and b = 0, once with learning rate 1 and once with learning rate 0.1 (ignoring rounding). What differs?
From zero, every update is the learning rate times the same vector, so all weights and scores are scaled by the same positive number. Signs do not change, so the same examples are mistakes in the same order. The number of epochs is unchanged. The run still stops, since the theorem’s bound does not depend on the rate. The direction of each update does not depend on the rate either.
What does the perceptron convergence theorem guarantee?
The bound needs a separating line to exist, and then the number of updates is limited by the squared ratio of the input radius to the margin. It says nothing useful about data that is not separable. The rule stops at the first line that separates the data, which is not the widest-margin line. The number of epochs is not tied to the number of points.
On XOR the widget shows 4 mistakes in each of 1000 epochs. Which conclusion is correct?
The four inequalities for a separating line contradict each other, so every line gets at least one of the four wrong, whatever the rate, start or order. The run can only stop when an epoch has zero mistakes, which would mean a separating line. A new rate, start or order changes the path and does not change that fact.
For a misclassified example, what is the gradient of the loss max(0, −y(w·x + b)) with respect to w?
When the example is wrong the loss equals −y(w·x + b), whose gradient with respect to w is −y·x. A gradient-descent step subtracts η times it, which is the perceptron update w + η·y·x. The positive version is the update itself, not the gradient. The plain x ignores the label. The gradient is 0 only for correctly classified examples.
Exercises
- Let , , and the example with . Is it a mistake? If so, give the new , and the new score.
Show answer
The score is , and , so it is a mistake. and . The new score is . The change is , which equals . The score is still positive, so this example is not yet right: one update was not enough. - Run the first epoch of AND by hand (order , labels , zero start, ).
Show answer
: score , mistake, , . : score , correct. : score , correct. : score with , a mistake, so , . Two mistakes, ending at , . - In the 0/1 form, an example has target and the perceptron outputs . Write the update, and compare it with the form.
Show answer
, so and . In the form the label is , so the update is , the same. - Show that XNOR (labels at and , at and ) is not linearly separable either.
Show answer
The inequalities are , , and . Adding the middle two gives , so , which contradicts the last one. - The data is with and with , in one dimension. Find , a margin and the bound, then run the rule from zero with and count the updates.
Show answer
With the bias input, the inputs are and , so . The unit vector gives for both, so and the bound is . The run: has score , a mistake, giving , . has score , a mistake, giving , . Then both are correct. Two updates, so the bound is tight here. - Why does the pocket algorithm keep a separate copy of the best weights instead of just returning the last weights?
Show answer
On non-separable data the running weights keep changing, and the last weights can be much worse than earlier ones (8 of 14 right after epoch 50, against 13 of 14 for the best weights seen). The pocket remembers the best set it has seen.