Learn ML

Chapter 6 of 25

The Perceptron

The first learning machine that could draw a line

15 min read

Motivation

Imagine you had to decide, from scratch, how to separate spam emails from real ones using only two numbers: how many exclamation marks are in the subject line, and how many links are in the body. You'd probably do something very human — draw an imaginary line in your head. "If there are a lot of exclamation marks and a lot of links, it's spam. Otherwise, it's probably fine."

That imaginary line is exactly what the perceptron does, except it draws the line automatically, from data, instead of you guessing it by hand. It was the first machine that could look at labeled examples and learn where to put that line by itself. Everything else in this course — every layer, every activation function, every optimizer — exists because this one idea, powerful as it was, eventually ran into a wall.

A Real-Life Scenario

Picture a bank trying to automatically decide whether to approve a loan based on two pieces of information: the applicant's income and their existing debt. Plot every past applicant as a point on a graph — income on one axis, debt on the other — and color each point green (approved) or red (denied).

If the green points and red points naturally cluster into two separate regions that could be split by a single straight line, a perceptron can find that line for you. It watches the bank's past decisions, adjusts itself every time it gets one wrong, and eventually lands on a line that matches the bank's historical behavior. No one had to write "if income > X and debt < Y" — the machine derived its own rule.

Building the Intuition

Before any equations, here's the mental picture to hold onto:

  • Every input feature (income, debt, pixel brightness, word count — anything) is a number.
  • The perceptron multiplies each input by a weight that says how important that input is, adds them all up, and adds one more number called the bias that shifts the decision left or right.
  • If that sum crosses a threshold, it fires "yes" (class 1). Otherwise it stays quiet ("class 0").

Geometrically, "the sum crosses a threshold" is just another way of saying "the point is on one side of a line." In two dimensions that boundary is a straight line. In three dimensions it's a flat plane. In higher dimensions — which is where most real problems live — it's called a hyperplane, but the idea never changes: the perceptron only ever learns one straight cut through the data.

Perceptron Playground

Add points for two classes, then step through the learning rule and watch the boundary line move to correct mistakes.

Click the grid to add a point:

w = (0.10, 0.10), b = 0.00

The Math Behind It

Making a Prediction

Perceptron Output
z=wx+b=i=1nwixi+b,y^=φ(z)={1if z00if z<0z = \mathbf{w}^\top \mathbf{x} + b = \sum_{i=1}^n w_i x_i + b, \qquad \hat{y} = \varphi(z) = \begin{cases} 1 & \text{if } z \geq 0 \\ 0 & \text{if } z < 0 \end{cases}

Where: x\mathbf{x} is the input feature vector, w\mathbf{w} is the weight vector, bb is the bias, zz is the pre-activation (the raw weighted sum), φ\varphi is the Heaviside step function, and y^\hat{y} is the predicted class label (0 or 1).

Intuition: Setting z=0z = 0 defines the boundary itself — wx+b=0\mathbf{w}^\top\mathbf{x} + b = 0 is the equation of the separating hyperplane. Everything on one side gets predicted as 1, everything on the other side as 0. The weights control the orientation of that boundary; the bias controls how far it sits from the origin.

Learning From Mistakes

The clever part isn't the neuron — a similar model existed years earlier. Rosenblatt's real contribution was a dead-simple, guaranteed rule for finding good weights automatically.

Perceptron Weight Update Rule
wiwi+η(yy^)xi,bb+η(yy^)w_i \leftarrow w_i + \eta (y - \hat{y}) x_i, \qquad b \leftarrow b + \eta(y - \hat{y})

Where: η>0\eta > 0 is the learning rate (how large each correction is), yy is the true label, y^\hat{y} is the predicted label, and (yy^)(y - \hat{y}) is the prediction error.

Intuition: If the prediction is already correct, yy^=0y - \hat{y} = 0 and nothing changes — the perceptron never touches weights it doesn't need to. If it predicted 0 but the answer was 1, the error is +1+1, and every weight gets nudged in the direction of that input, making zz larger next time. Get it backwards, and the nudge goes the other way. It's the smallest possible correction that fixes the mistake in front of it.

This is a special case of gradient descent

The perceptron rule looks hand-crafted, but it's actually gradient descent on a loss function (the "perceptron criterion") that only penalizes misclassified points. Chapter 12 formalizes what optimization theory means; the perceptron was doing it decades before the term was common.

The Convergence Guarantee — and Its Catch

Perceptron Convergence Theorem

If the training data is linearly separable, the perceptron learning algorithm is guaranteed to converge to weights that perfectly classify every training example, in a finite number of steps.

The guarantee has a hard precondition

"Linearly separable" is doing all the work in that theorem. If no straight line can separate the two classes, the perceptron will never settle down — it will oscillate forever, fixing one point at the expense of another. That single limitation is the entire subject of the next chapter, and it's what triggered the first AI winter.

Worked Example: Learning Logical AND

Let's hand-trace a perceptron learning the AND function, starting from all-zero weights and a learning rate of η=1\eta = 1.

Training data for logical AND
x₁x₂y (AND)
000
010
100
111

Epoch 1, example (0, 0), y=0y = 0: z=0    y^=1z = 0 \implies \hat{y} = 1 (wrong). Error =1= -1, so b1b \leftarrow -1 (weights stay 0, since x1=x2=0x_1=x_2=0).

Epoch 1, example (0, 1), y=0y = 0: z=1    y^=0z = -1 \implies \hat{y} = 0 — correct, no update.

Epoch 1, example (1, 0), y=0y = 0: z=1    y^=0z = -1 \implies \hat{y} = 0 — correct, no update.

Epoch 1, example (1, 1), y=1y = 1: z=1    y^=0z = -1 \implies \hat{y} = 0 (wrong). Error =+1= +1, so w11w_1 \leftarrow 1, w21w_2 \leftarrow 1, b0b \leftarrow 0.

After one epoch: w1=1,w2=1,b=0w_1 = 1, w_2 = 1, b = 0. Continuing this same check-and-correct loop for a few more epochs converges to something like w1=1,w2=1,b=2w_1 = 1, w_2 = 1, b = -2, which gives z=x1+x22z = x_1 + x_2 - 2 — exactly 2,1,1,0-2, -1, -1, 0 for the four rows, producing predictions 0,0,0,10, 0, 0, 1. That's the AND truth table, learned entirely from mistakes.

Exam technique

When tracing perceptron updates by hand, build a table with columns x1,x2,z,y^,y,error,Δw1,Δw2,Δbx_1, x_2, z, \hat{y}, y, \text{error}, \Delta w_1, \Delta w_2, \Delta b. It prevents arithmetic slips and makes partial credit easy for an examiner to award.

Implementing It

import numpy as np
 
class Perceptron:
    def __init__(self, n_inputs, learning_rate=1.0):
        self.w = np.zeros(n_inputs)
        self.b = 0.0
        self.lr = learning_rate
 
    def predict(self, x):
        z = np.dot(self.w, x) + self.b
        return 1 if z >= 0 else 0
 
    def fit(self, X, y, epochs=10):
        for epoch in range(epochs):
            errors = 0
            for xi, yi in zip(X, y):
                y_hat = self.predict(xi)
                error = yi - y_hat
                self.w += self.lr * error * xi
                self.b += self.lr * error
                errors += int(error != 0)
            print(f"Epoch {epoch+1}: mistakes = {errors}, w = {self.w}, b = {self.b:.2f}")
            if errors == 0:
                break
 
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
y = np.array([0, 0, 0, 1])
 
model = Perceptron(n_inputs=2, learning_rate=1.0)
model.fit(X, y, epochs=10)

A few things worth noticing about this code:

  • Zero-initialized weights are fine here. For a single perceptron there's no symmetry problem — every weight starts identical, but since there's only one neuron, there's no symmetry between neurons to break. That changes the moment we stack layers (Chapter 18).
  • The training loop stops early once a full epoch produces zero mistakes — the convergence theorem guarantees this will eventually happen, provided the data is linearly separable.
  • predict is the entire forward pass. There's no hidden layer, no chain of matrix multiplications — just one dot product and one comparison against zero.
Perceptron as a Single Artificial NeuronIllustration coming soon
Inputs are weighted, summed with a bias, and passed through a step function to produce one binary output.

Key Takeaways

Key Takeaways
  • The perceptron is a linear binary classifier: y^=φ(wx+b)\hat{y} = \varphi(\mathbf{w}^\top\mathbf{x} + b) with a step activation.
  • Its decision boundary is a hyperplane defined by wx+b=0\mathbf{w}^\top\mathbf{x} + b = 0.
  • The learning rule only updates weights on misclassified examples: wiwi+η(yy^)xiw_i \leftarrow w_i + \eta(y-\hat{y})x_i.
  • The Perceptron Convergence Theorem guarantees convergence — but only for linearly separable data.
  • It can learn AND, OR, and similar functions, but as the next chapter shows, it fundamentally cannot learn XOR.

Common Mistakes

Forgetting the bias term

Without a bias, the decision boundary is forced to pass through the origin. That's a huge, unnecessary restriction — always include and train the bias like any other weight.

Assuming the perceptron always converges

The convergence theorem has a precondition that's easy to skip past in a rush: the data has to be linearly separable. Plenty of real datasets aren't, and on those, training loss will oscillate forever rather than settle to zero.

Interview Corner

Quick Check
1. What happens to the perceptron weights when a prediction is already correct?
2. Why does the Perceptron Convergence Theorem not guarantee a solution for the XOR problem?

Where This Shows Up in Practice

Standalone perceptrons are rarely deployed today, but the idea never disappeared — it became the basic building block of every neuron inside a modern neural network. Understanding exactly what one perceptron can and can't do is the fastest path to understanding why deep learning stacks so many of them together, which is precisely where the next two chapters are headed.