◆ AI All-in-One

Level 3 In-Depth AI · Deep Learning

The Perceptron

The first learning machine modelled on a brain cell. It weighs its inputs, adds them up and fires if the total passes a threshold. Its simple learning rule, and its famous failure on XOR, set the stage for all of deep learning.

Level
●●●●● Beginner
Reading
14 min
To learn it well
45 minutes to read, an hour to practise
↗ Plan a path here

Read first

VectorsSupervised Learning

This leads to

Neural Networks
The full path from zero — 5 concepts before this one
  1. What Is AI?
  2. Vectors
  3. How Machines Learn
  4. Supervised, Unsupervised and Reinforcement Learning
  5. Supervised Learning
  6. The Perceptron

Read them roughly in this order. See it on the concept map →

Why it matters

Every neural network, from the one that unlocks your phone with your face to the language models that write text, is built from millions or billions of copies of one small unit: the artificial neuron. The perceptron is the original artificial neuron that could learn. If you understand it, you understand the basic brick of deep learning.

The perceptron also teaches two lessons that shaped the whole history of AI. First, a machine can learn a decision from examples with a rule so simple you can run it with pencil and paper. Second, a single neuron has a hard limit: it can only draw straight lines. The search for a way past that limit led to multi-layer networks, Backpropagation and, eventually, modern AI.

The intuition

Think about how you decide whether to go to a concert tonight. You weigh a few pieces of evidence:

  • Is it raining? That counts against going, and quite strongly.
  • Is your friend going? That counts for going, even more strongly.
  • Are the tickets cheap? That counts for going, a little.

You add up the evidence, each piece multiplied by how much it matters to you, and if the total passes some threshold, you go. That is exactly what a perceptron does.

x₁ rainy? = 1 x₂ friend going? = 1 x₃ tickets cheap? = 0 w₁ = −2 w₂ = 3 w₃ = 1 b bias b = −0.5 shifts the threshold Σ z = w₁x₁ + w₂x₂ + w₃x₃ + b = −2·1 + 3·1 + 1·0 − 0.5 = 0.5 → ŷ = 1 (go) step 1 if z > 0, else 0 ŷ output 1 = go, 0 = stay
Fig. 1 A perceptron deciding whether to go to a concert. Each input is multiplied by its weight, the results are added together with a bias, and a step function turns the total into a yes-or-no answer.

Each input gets a weight, a number that says how much that input matters and in which direction. Positive weights push towards "yes", negative weights push towards "no". The perceptron adds up the weighted inputs to get a weighted sum, adds a bias (a number that makes it easier or harder to say yes overall), and then makes a hard decision: if the total is above zero, output 1; otherwise output 0.

The name comes from biology. A real brain cell, a neuron, receives signals from other cells through connections of different strengths, and "fires" an electrical pulse if the combined input is strong enough. The perceptron is a very simplified cartoon of that. Modern AI owes far more to maths than to biology, but the cartoon stuck.

What makes the perceptron more than a fixed formula is that it learns its weights from examples. Show it a case, check its answer, and if it was wrong, nudge the weights so that it would be a little less wrong next time.

Key idea A perceptron computes a weighted sum of its inputs plus a bias and outputs 1 if that sum is positive. Learning means adjusting the weights whenever it makes a mistake.

How it works

The forward computation

Collect the inputs into a vector x=(x1,x2,…,xn)\mathbf{x} = (x_1, x_2, \dots, x_n) and the weights into a vector w=(w1,w2,…,wn)\mathbf{w} = (w_1, w_2, \dots, w_n). The perceptron first computes the weighted sum plus the bias bb. Call it zz:

z=w1x1+w2x2+⋯+wnxn+b=w⋅x+bz = w_1 x_1 + w_2 x_2 + \dots + w_n x_n + b = \mathbf{w} \cdot \mathbf{x} + b

The dot ⋅\cdot is the dot product: multiply matching entries and add them up. Then it applies a step function, which jumps from 0 to 1 at zero:

y^={1if z>00otherwise\hat{y} = \begin{cases} 1 & \text{if } z > 0 \\ 0 & \text{otherwise} \end{cases}

The hat on y^\hat{y} ("y-hat") marks it as the model's prediction, as opposed to the true answer yy.

In the concert example, the inputs are x=(1,1,0)\mathbf{x} = (1, 1, 0) (raining, friend going, tickets not cheap), the weights are w=(−2,3,1)\mathbf{w} = (-2, 3, 1) and the bias is b=−0.5b = -0.5:

z=(−2)(1)+(3)(1)+(1)(0)−0.5=0.5z = (-2)(1) + (3)(1) + (1)(0) - 0.5 = 0.5

Since 0.5>00.5 > 0, the perceptron outputs y^=1\hat{y} = 1: go. If your friend cancels, x2x_2 becomes 0, z=−2.5z = -2.5, and the answer flips to 0.

The geometry: a line that splits the space

Here is the picture that explains both the power and the weakness of the perceptron. With two inputs, every example is a point (x1,x2)(x_1, x_2) on a flat plane. The perceptron says 1 on one side of the set of points where z=0z = 0, and 0 on the other. That set,

w1x1+w2x2+b=0,w_1 x_1 + w_2 x_2 + b = 0,

is a straight line. It is called the decision boundary. The weights set the line's tilt and the bias slides it back and forth. With three inputs the boundary is a flat plane in 3-D space, and with more inputs it is a flat "hyperplane" that you can't picture but that behaves the same way.

So a perceptron can only ever make decisions of the form "which side of a straight cut is this point on?" Problems that can be solved this way are called linearly separable.

The learning rule

Now the learning part. We have labelled training examples, pairs of an input x\mathbf{x} and a correct answer yy that is either 0 or 1. This is Supervised Learning. Start with all weights and the bias at zero, then go through the examples one at a time:

  1. Compute the prediction y^\hat{y}.
  2. Compute the error y−y^y - \hat{y}. It can only be 00 (correct), +1+1 (said 0, should have said 1) or −1-1 (said 1, should have said 0).
  3. Update every weight and the bias:
wi←wi+η (y−y^) xib←b+η (y−y^)w_i \leftarrow w_i + \eta \, (y - \hat{y}) \, x_i \qquad b \leftarrow b + \eta \, (y - \hat{y})

The arrow means "replace with". The learning rate η\eta ("eta") scales the size of the nudge. For the classic perceptron, η=1\eta = 1 works fine.

Why does this make sense? If the answer was right, the error is 0 and nothing changes. If the perceptron said 0 but should have said 1, the error is +1+1, so we add the input to the weights. That raises zz the next time we see this input, because w⋅x\mathbf{w} \cdot \mathbf{x} grows by x⋅x\mathbf{x} \cdot \mathbf{x}, which is positive. If it said 1 but should have said 0, we subtract the input, which lowers zz. Inputs that were 0 don't change their weights at all, since they played no part in the mistake. This is the perceptron learning rule.

A worked example: learning AND

The logical function AND outputs 1 only when both inputs are 1. Four examples, starting from w=(0,0)\mathbf{w} = (0, 0), b=0b = 0, η=1\eta = 1:

Pass Input x\mathbf{x} Target yy z=w⋅x+bz = \mathbf{w}\cdot\mathbf{x} + b Prediction Error New w\mathbf{w}, bb
1 (0, 0) 0 0 0 0 (0, 0), 0
1 (0, 1) 0 0 0 0 (0, 0), 0
1 (1, 0) 0 0 0 0 (0, 0), 0
1 (1, 1) 1 0 0 +1 (1, 1), 1
2 (0, 0) 0 1 1 −1 (1, 1), 0
2 (0, 1) 0 1 1 −1 (1, 0), −1
2 (1, 0) 0 0 0 0 (1, 0), −1
2 (1, 1) 1 0 0 +1 (2, 1), 0

Follow one row by hand. In pass 2, at input (0, 1), the weights are (1, 1) and the bias is 0, so z=1⋅0+1⋅1+0=1z = 1 \cdot 0 + 1 \cdot 1 + 0 = 1, the prediction is 1 and the target is 0. The error is −1-1. So w1w_1 changes by −1×0=0-1 \times 0 = 0, w2w_2 changes by −1×1=−1-1 \times 1 = -1, and bb changes by −1-1. The result is w=(1,0)\mathbf{w} = (1, 0), b=−1b = -1.

Keep going and the weights wobble for a few more passes. In the sixth pass through the data the perceptron makes no mistakes, with w=(2,1)\mathbf{w} = (2, 1) and b=−2b = -2. Check: for (1, 1), z=2+1−2=1>0z = 2 + 1 - 2 = 1 > 0, output 1. For (1, 0), z=2−2=0z = 2 - 2 = 0, not above zero, output 0. For (0, 1), z=−1z = -1, and for (0, 0), z=−2z = -2, both output 0. All four are correct. One full pass through the training data is an epoch, so this took six epochs.

The convergence guarantee

The perceptron comes with a remarkable promise, the perceptron convergence theorem (proved by Albert Novikoff in 1962). If the data are linearly separable, the learning rule is guaranteed to find a separating line after a finite number of mistakes. The bound even says how many: at most (R/γ)2(R/\gamma)^2, where RR is the length of the longest input vector and γ\gamma ("gamma") is the margin, the gap between the best possible line and the nearest example. Wide gaps mean fast learning. Tight squeezes mean slow learning.

The flip side is just as important. If the data are not linearly separable, the rule never settles. It keeps making mistakes and the weights keep cycling forever.

The XOR problem

That brings us to the most famous failure in AI history. The function XOR ("exclusive or") outputs 1 when exactly one of its two inputs is 1:

x1x_1 x2x_2 AND OR XOR
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0

Plot the four points and colour them by the answer:

AND x₁ x₂ one line separates x₁ + x₂ − 1.5 > 0 OR x₁ x₂ one line separates x₁ + x₂ − 0.5 > 0 XOR x₁ x₂ no single line works the 1s sit on opposite corners output 1 output 0 decision boundary
Fig. 2 AND and OR can each be solved by one straight line. For XOR the two 1s sit on opposite corners of the square, so every straight line leaves at least one point on the wrong side.

For XOR, the 1s sit at (0, 1) and (1, 0), on opposite corners. The 0s sit on the other two corners. No straight line can put both 1s on one side and both 0s on the other. You can prove it in two lines. To get (0, 0) right we need b≤0b \le 0. To get (0, 1) and (1, 0) right we need w2+b>0w_2 + b > 0 and w1+b>0w_1 + b > 0. Adding those gives w1+w2+2b>0w_1 + w_2 + 2b > 0, so w1+w2+b>−b≥0w_1 + w_2 + b > -b \ge 0, which means (1, 1) is classified as 1. Wrong. A single perceptron cannot compute XOR, however long you train it.

This is the XOR problem. It is not a curiosity. Many real patterns have the same shape: "this feature matters, but only when that other one is absent". The fix, as you'll see in Neural Networks, is to stack perceptrons in layers. A hidden layer can compute OR and AND separately, and an output neuron can combine them into "OR but not AND", which is XOR.

In code

The perceptron in plain NumPy, trained on AND. It reproduces the hand-worked table.

import numpy as np

# The four possible inputs and the AND labels
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
y = np.array([0, 0, 0, 1])

w = np.zeros(2)   # weights
b = 0.0           # bias
lr = 1.0          # learning rate

for epoch in range(10):
    mistakes = 0
    for xi, target in zip(X, y):
        pred = 1 if xi @ w + b > 0 else 0      # weighted sum, then step
        error = target - pred                  # +1, 0 or -1
        if error != 0:
            w += lr * error * xi               # the perceptron rule
            b += lr * error
            mistakes += 1
    print(f"epoch {epoch}: mistakes {mistakes}  w {w}  b {b}")
    if mistakes == 0:
        break

print("predictions:", [(1 if xi @ w + b > 0 else 0) for xi in X])

# epoch 0: mistakes 1  w [1. 1.]  b 1.0
# epoch 1: mistakes 3  w [2. 1.]  b 0.0
# epoch 2: mistakes 3  w [2. 1.]  b -1.0
# epoch 3: mistakes 2  w [2. 2.]  b -1.0
# epoch 4: mistakes 1  w [2. 1.]  b -2.0
# epoch 5: mistakes 0  w [2. 1.]  b -2.0
# predictions: [0, 0, 0, 1]

Change y to the XOR labels [0, 1, 1, 0] and set the loop to 100 epochs. The mistake count never reaches 0. After 100 epochs it is still making 4 mistakes per pass.

scikit-learn has a ready-made version:

import numpy as np
from sklearn.linear_model import Perceptron

X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
for name, y in [("AND", [0, 0, 0, 1]), ("XOR", [0, 1, 1, 0])]:
    clf = Perceptron(max_iter=1000, tol=None, random_state=0).fit(X, y)
    print(name, clf.predict(X), "accuracy", clf.score(X, y))

# AND [0 0 0 1] accuracy 1.0
# XOR [0 0 0 0] accuracy 0.5

On XOR it gives up and does no better than a coin.

Common pitfalls

  • Forgetting the bias. Without bb, the decision boundary must pass through the origin. Many simple problems, including AND, become impossible. Every neuron in every modern network has a bias for this reason.
  • Unscaled inputs. If one input is measured in thousands and another in fractions, the big one dominates every update and learning crawls. Standardise your inputs first.
  • Waiting for convergence that never comes. On data that isn't linearly separable, which is most real data, the plain perceptron cycles forever. Always cap the number of epochs. Variants such as the pocket algorithm keep the best weights seen so far, and the averaged perceptron averages the weights over all steps, which is more stable.
  • Reading the output as a probability. The step function outputs only 0 or 1. It has no notion of "probably yes". If you want a confidence, use Logistic Regression, which replaces the step with a smooth S-curve.

Watch out The step function has a slope of zero everywhere (and no slope at all at the jump). That means Gradient Descent gets no signal from it. This is why modern networks replace the step with smooth Activation Functions such as the sigmoid or ReLU. Without that change, Backpropagation could not train multi-layer networks.

Where it leads

  • Logistic regression keeps the weighted sum but swaps the step for a smooth sigmoid curve, giving probabilities and a loss you can minimise with gradient descent. See Logistic Regression.
  • Support vector machines look for the separating line with the widest margin, rather than any line that works. See Support Vector Machines.
  • Multi-layer networks stack many neurons in layers, which lets them carve out curved and patchy regions and solve XOR easily. See Neural Networks.
  • The modern neuron is the perceptron with two upgrades: a smooth activation function in place of the step, and weights learned by Backpropagation instead of the perceptron rule.

A bit of history

In 1943, the neurophysiologist Warren McCulloch and the logician Walter Pitts described a simplified model neuron that summed binary inputs and fired above a threshold. They showed that networks of such units could compute logical functions, but their weights were set by hand.

In 1958, the psychologist Frank Rosenblatt at the Cornell Aeronautical Laboratory published the perceptron, a neuron that learned its weights from examples. He built it in hardware as the Mark I Perceptron, which used a grid of 400 light sensors and motor-driven potentiometers as adjustable weights, and trained it to recognise simple shapes. The press coverage was breathless and predicted machines that would soon walk, talk and think.

In 1969, Marvin Minsky and Seymour Papert published the book Perceptrons, a careful mathematical analysis of what single-layer perceptrons can and cannot compute, with XOR-like problems as a central example. Multi-layer networks were known to be more powerful, but nobody had a good way to train them. The book is often blamed, probably too simply, for a long drop in neural-network funding in the 1970s. The way out, Backpropagation for multi-layer networks, became widely known in 1986. See A Short History of AI for the longer story.

Try it

  1. Train the NumPy perceptron on OR (y = [0, 1, 1, 1]). How many epochs does it take, and what weights does it find? Draw its decision boundary on the square.
  2. Find, by hand, weights and a bias that make a perceptron compute NOT-AND ("NAND": 0 only when both inputs are 1).
  3. Harder: XOR is "OR but not AND". Using your OR and NAND perceptrons as two hidden units, and an AND perceptron on top of their outputs, build a three-neuron network that computes XOR. Check all four inputs.

Hint for 3: XOR(a, b) = AND(OR(a, b), NAND(a, b)). Feed the two hidden outputs into the AND perceptron as if they were ordinary inputs.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. A perceptron has weights (−2, 3, 1) and bias −0.5. The input is (1, 0, 1). What does it output?

  2. During training the perceptron says 1 for an example whose true label is 0. What does the learning rule do to the weights?

  3. You train a plain perceptron for 1,000 epochs and it is still making mistakes every pass, with weights that keep cycling. What is the most likely explanation?

  4. Why can a single perceptron never compute XOR?

  5. You remove the bias from a perceptron. What can it no longer do?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Video

Neural Networks (video series)

3Blue1Brown · Beginner · Free

Gorgeous animated explanations of neural nets, gradient descent, backprop, Transformers and attention.

Book

Neural Networks and Deep Learning

Michael Nielsen · 2015 · Beginner · Free

A free online book that builds a handwritten-digit classifier from scratch in Python, explaining every step of perceptrons, sigmoid neurons, backpropagation and training tricks with great clarity.

Book

Dive into Deep Learning

Zhang, Lipton, Li & Smola · Intermediate · Free

An interactive book with maths, figures and runnable PyTorch code for every chapter. Many universities use it.

Interactive

TensorFlow Playground

Google · Beginner · Free

Train a small neural network in your browser and watch it learn decision boundaries live.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/dl/perceptron.md