Reading history

The Perceptron Algorithm in Python

6 min read 0 views

Learn the perceptron algorithm in Python: code the learning rule from scratch, watch it find a line, and see why it cannot learn XOR.

The perceptron is the oldest learning machine still taught today. It was invented in 1958 and is the simplest kind of artificial neuron. It draws a straight line between two classes and nudges that line every time it makes a mistake. In this lesson you will code the perceptron rule from scratch, watch it learn, and see the famous problem it cannot solve.

In this lesson you will learn

  • How a perceptron turns inputs into a yes/no answer
  • The perceptron learning rule, step by step
  • Why centring the data helps it learn faster
  • Why a single perceptron cannot learn XOR
  • How extra features or more layers fix that

You should know logistic regression. This lesson leads into neural networks.

How a Perceptron Decides

A perceptron takes some inputs, multiplies each by a weight, adds them up, and adds a bias. If the total is above 0 it answers 1. Otherwise it answers 0.

output = 1 if (w1 x x1 + w2 x x2 + b) > 0, else 0

The line where the total is exactly 0 is the decision boundary. Points on one side get 1, and points on the other side get 0. Learning means finding weights that put this line in the right place.

02468100246810Hours studiedHours sleptnewboundarypass (1)fail (0)Line: 4(study-5) +3(sleep-5) + 1 = 0

The Learning Rule

The rule is short. For each training point:

  1. Make a guess with the current weights.
  2. Find the error: true answer minus guess. It is +1, 0 or -1.
  3. If the error is 0, do nothing.
  4. Otherwise, add error x input to the weights and add the error to the bias.

If the perceptron said 0 but the answer was 1, the weights move towards that point. If it said 1 but the answer was 0, they move away. One full pass over the data is an epoch.

A Perceptron From Scratch

Eight students: did they pass, based on hours studied and hours slept? We subtract 5 from every value first so the data sits around zero.

import numpy as np

# The perceptron learning rule on a tiny problem: pass (1) or fail (0)
# from hours studied and hours slept.
raw = np.array([[2, 4], [1, 6], [3, 3], [2, 7], [6, 7], [7, 5], [5, 8], [8, 6]], dtype=float)
y = np.array([0, 0, 0, 0, 1, 1, 1, 1])
X = raw - 5          # centre the data around 0; the perceptron learns much faster

w = np.zeros(2)      # one weight per input
b = 0.0              # bias

for epoch in range(1, 11):
    mistakes = 0
    for xi, target in zip(X, y):
        guess = 1 if xi @ w + b > 0 else 0       # step function
        error = target - guess                   # -1, 0 or +1
        if error != 0:
            w += error * xi                      # move the line towards the point
            b += error
            mistakes += 1
    print(f"epoch {epoch}: {mistakes} mistakes, w = {w}, b = {b}")
    if mistakes == 0:
        break

print("predictions:", (X @ w + b > 0).astype(int))
new = np.array([4, 5]) - 5
print("new student (4 h study, 5 h sleep):", int(new @ w + b > 0))

Output

epoch 1: 1 mistakes, w = [1. 2.], b = 1.0
epoch 2: 2 mistakes, w = [4. 3.], b = 1.0
epoch 3: 0 mistakes, w = [4. 3.], b = 1.0
predictions: [0 0 0 0 1 1 1 1]
new student (4 h study, 5 h sleep): 0
  • In epoch 1 the perceptron makes one mistake and moves its line. In epoch 2 it makes two more. In epoch 3 it makes none, so it stops.
  • The final rule is 4 x (study – 5) + 3 x (sleep – 5) + 1 > 0. Study hours carry more weight than sleep.
  • The new student with 4 hours of study and 5 of sleep gets 4 x (-1) + 0 + 1 = -3, which is below 0, so the answer is fail.
  • Without centring, the same data takes 26 epochs. The bias moves by only 1 per mistake, so it needs many steps to reach a big value. Centring is a simple form of feature scaling.

The convergence promise

If a straight line can separate the two classes perfectly, the perceptron rule is proven to find one in a limited number of steps. If no such line exists, it never settles. It keeps moving the line forever.

The XOR Problem

XOR (“exclusive or”) is 1 when exactly one of its two inputs is 1. Put the four points on a grid. The two 1s sit at opposite corners, and so do the two 0s. No single straight line can put both 1s on one side and both 0s on the other.

import numpy as np
from sklearn.linear_model import Perceptron

# XOR: output is 1 when exactly one input is 1. No single straight line splits it.
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
for name, y in [("AND", [0, 0, 0, 1]), ("OR", [0, 1, 1, 1]), ("XOR", [0, 1, 1, 0])]:
    p = Perceptron(max_iter=100, random_state=0).fit(X, y)
    print(f"{name}: predictions {p.predict(X)}, accuracy {p.score(X, y):.2f}")

# Fix for XOR: add a third input x1*x2. Now a flat plane can split the points.
X3 = np.column_stack([X, X[:, 0] * X[:, 1]])
p = Perceptron(max_iter=100, random_state=0).fit(X3, [0, 1, 1, 0])
print(f"XOR with x1*x2 added: predictions {p.predict(X3)}, accuracy {p.score(X3, [0, 1, 1, 0]):.2f}")

Output

AND: predictions [0 0 0 1], accuracy 1.00
OR: predictions [0 1 1 1], accuracy 1.00
XOR: predictions [0 0 0 0], accuracy 0.50
XOR with x1*x2 added: predictions [0 1 1 0], accuracy 1.00
  • scikit-learn’s Perceptron learns AND and OR perfectly, because a line can split both.
  • On XOR it gets only 50%, no better than a coin flip.
  • Adding a third input, x1 x x2, lifts the points into 3D. Now a flat plane can separate them, and the perceptron scores 100%.

In 1969, the book Perceptrons by Minsky and Papert pointed out this limit, and interest in neural networks fell for years. The lasting fix is to stack perceptrons in layers. A hidden layer can build features like x1 x x2 by itself. That is a multi-layer neural network, trained with backpropagation.

Perceptron vs Logistic Regression

PerceptronLogistic regression
OutputHard 0 or 1Probability from 0 to 1
UpdatesOnly on mistakesOn every point, by how wrong it is
Non-separable dataNever settlesSettles on the best line
Line foundAny line that worksOne best line

Common Mistakes

  1. Forgetting the bias. Without it, the line must pass through the origin, which often makes the problem impossible.
  2. Skipping scaling. Large or off-centre inputs make learning slow, as the 26-epoch run shows.
  3. Expecting it to solve curved problems. A single perceptron only draws straight lines.
  4. Running forever on noisy data. Always set a maximum number of epochs.

Practice Exercises

Exercise 1. With the final weights from pc1.py, does a student with 6 hours of study and 3 hours of sleep pass?

Show answer

Centre first: study 6 – 5 = 1, sleep 3 – 5 = -2. Total = 4 x 1 + 3 x (-2) + 1 = -1. That is below 0, so the perceptron predicts fail.

Exercise 2. Can a single perceptron learn NAND (1 unless both inputs are 1)?

Show answer

Yes. Only the corner (1, 1) gives 0, so one straight line can cut that corner off. For example, w1 = w2 = -1 and b = 1.5 works.

Frequently Asked Questions

Is a perceptron the same as a neuron in a neural network?

It is the simplest version. Modern neurons use smooth activation functions such as ReLU or sigmoid instead of a hard step, which allows training with gradients.

Why can’t a perceptron learn XOR?

A perceptron can only draw one straight line. The XOR points that give 1 sit at opposite corners of a square, so no single line can separate them from the points that give 0.

Should I use a perceptron in real projects?

Rarely. Logistic regression or a linear SVM usually works better. The perceptron is mainly valuable for understanding how neural networks learn.

Summary

  • A perceptron adds weighted inputs and a bias, then outputs 1 if the total is above 0.
  • It learns by moving its line only when it makes a mistake.
  • It always succeeds if a straight line can separate the classes.
  • It cannot learn XOR; extra features or hidden layers fix this.

Next: Comparing Machine Learning Models with Statistical Tests.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *