CadetX
CX Learn | Complete Neural Networks Guide
TensorFlow · Keras
CadetX logo CadetX CX Learn
NN-101 · Module 2 Beginner about 35 minutes 8 Lessons Prereq: Module 1, basic Python and NumPy

The Perceptron & Artificial Neuron

The perceptron is the simplest neural network there is: a single neuron that learns to make yes-or-no decisions. Invented in 1958, it's the ancestor of every modern network. In this module you'll see exactly how it thinks, watch it learn, discover its famous weakness, and build one from scratch in Python.

  • Level: Beginner
  • Time: about 35 minutes
  • Needs: Module 1, basic Python and NumPy

By the end of this module you will be able to

  • Explain how a perceptron turns inputs into a yes/no decision
  • Work out a perceptron's output by hand
  • Describe what the weights and bias do to the decision boundary
  • Apply the perceptron learning rule step by step
  • Explain the XOR problem and why hidden layers solve it
  • Explain why modern neurons use smooth activation functions
  • Build and train a perceptron from scratch in Python

2.1What is a perceptron?

In 1958, psychologist Frank Rosenblatt built a machine called the Mark I Perceptron. It was a room-sized machine wired to a 20 × 20 grid of light sensors, and it could learn to tell simple shapes apart. Newspapers at the time were very excited about machines that could "learn".

The idea behind it is simple. A perceptron is a single artificial neuron that:

  1. takes some inputs,
  2. multiplies each one by a weight and adds them up, plus a bias,
  3. outputs 1 ("yes") if the total is zero or more, and 0 ("no") if it's below zero.
A perceptron: inputs x1 and x2 are multiplied by weights w1 and w2, added together with a bias, and passed through a step function that outputs 1 if the total is zero or more, and 0 otherwise.x₁w₁x₂w₂+ bias bΣStep functionOutput1 or 0total = w₁x₁ + w₂x₂ + btotal ≥ 0 → 1total < 0 → 0
Figure 1. A perceptron with two inputs. It's the same neuron you met in Module 1, but with a step function as its activation: a hard switch that's either off (0) or on (1).

The perceptron in one sentence

A perceptron is a single neuron that adds up its weighted inputs and bias, then says "yes" if the total reaches zero and "no" if it doesn't.

2.2Working out a perceptron by hand

A college uses a perceptron to flag whether a student is likely to pass an exam, based on two inputs: hours studied (x₁) and hours of sleep the night before (x₂). Its weights are w₁ = 0.6 and w₂ = 0.4, and its bias is b = −5.

StudentStudied (x₁)Slept (x₂)Total = 0.6x₁ + 0.4x₂ − 5Output
Aisha874.8 + 2.8 − 5 = 2.61 (pass)
Ben381.8 + 3.2 − 5 = 0.01 (just!)
Chloe533.0 + 1.2 − 5 = −0.80 (fail)
Dev241.2 + 1.6 − 5 = −2.20 (fail)

That's all a perceptron does. Notice how studying counts more than sleep (0.6 vs 0.4), and the bias of −5 means a student needs a fair amount of both to reach the "pass" line.

What the weights and bias do

PartEffect
Big positive weightThat input strongly pushes towards "yes"
Negative weightThat input pushes towards "no"
Weight near 0That input barely matters
BiasHow easy it is to say "yes" overall. A very negative bias means "hard to convince"; a positive bias means "says yes easily"

2.3How a perceptron learns

In the example above, we chose the weights. The real magic of Rosenblatt's perceptron is that it can learn them from examples, using a very simple rule. For every training example:

  1. Predict: work out the output (0 or 1).
  2. Compare: error = correct answer − prediction. This can only be +1 (said no, should have said yes), −1 (said yes, should have said no) or 0 (correct).
  3. Adjust: if there was an error, nudge each weight and the bias in the direction that fixes it.
new weight = weight + learning rate × error × input
new bias = bias + learning rate × error

If the answer was right, the error is 0 and nothing changes. If the perceptron said "no" when it should have said "yes", the weights on the active inputs go up, making "yes" more likely next time. And the opposite for a wrong "yes".

Watching it learn the AND rule

The AND rule outputs 1 only when both inputs are 1. Let's train a perceptron on it, starting with all weights at 0 and a learning rate of 0.1. Here are the first two epochs (real values from the Python code in lesson 2.7):

EpochInputCorrectPredictedErrorWeights afterBias after
1(0, 0)01−1(0, 0)−0.1
1(0, 1)000(0, 0)−0.1
1(1, 0)000(0, 0)−0.1
1(1, 1)10+1(0.1, 0.1)0.0
2(0, 0)01−1(0.1, 0.1)−0.1
2(0, 1)01−1(0.1, 0)−0.2
2(1, 0)000(0.1, 0)−0.2
2(1, 1)10+1(0.2, 0.1)−0.1

After 4 epochs, every answer is correct and the weights stop changing. The perceptron has learned AND by itself.

2.4The decision boundary

Remember logistic regression from the Machine Learning track? A perceptron draws the same kind of boundary: a straight line. Everything on one side gets 1, everything on the other side gets 0. The weights set the angle of the line, and the bias shifts it.

Every time the perceptron makes a mistake and updates its weights, the line moves a little. Watch it happen with 26 students:

Try it: train a perceptron step by step

PassedFailedWrong right now

The learning rate

The learning rate controls how big each nudge is (0.1 in the lab). Here's a surprise: for a perceptron that starts with all weights at zero, the learning rate makes no difference to where the line ends up. Every weight and the bias get scaled by the same amount, so the line is in exactly the same place. In modern networks it's a very different story: choosing a good learning rate is one of the most important decisions you'll make (Module 4).

A famous guarantee

Rosenblatt proved that if the two groups can be separated by a straight line, the perceptron learning rule is guaranteed to find one eventually. This is called the perceptron convergence theorem. The catch is that big "if"…

2.5The XOR problem

Some problems can't be solved with one straight line. The most famous is XOR ("exclusive or"): the answer is 1 when exactly one input is 1, but 0 when both are 0 or both are 1. For example: "I'll go out if either Sam or Alex comes, but not both, because they don't get on."

Three logic gates plotted as four points each. For AND and OR, one straight line separates the 1s from the 0s. For XOR, the 1s are on opposite corners and no single straight line can separate them.0001AND0111OR0110?XOROne line worksOne line worksNo single line works
Figure 2. Four inputs for each rule; amber = 1, blue = 0. AND and OR can each be split with one line. For XOR, the 1s sit on opposite corners, so any straight line leaves a mistake.

A single perceptron can never learn XOR, however long you train it. In the Python example, it gets stuck at 2 out of 4 correct.

In 1969, Marvin Minsky and Seymour Papert published a book, Perceptrons, which set out limits like this in detail. Research funding for neural networks dried up for years, a period now called the first "AI winter".

The solution: add a hidden layer

The fix is to use more than one neuron, in layers. Two hidden neurons can each draw their own line, and an output neuron combines them:

A two-layer network that solves XOR. Two hidden neurons compute OR and NAND of the inputs; an output neuron combines them with AND. The result is 1 only when exactly one input is 1.x₁inputx₂inputOR"at least one"NAND"not both"ANDboth hidden say yesXORInputsHidden layerOutput
Figure 3. XOR solved with three perceptrons. One hidden neuron checks "is at least one input on?" (OR), another checks "are they not both on?" (NAND). The output neuron says yes only when both hidden neurons agree (AND). That's exactly XOR.
x₁x₂ORNANDOutput: OR AND NANDXOR
000100
011111
101111
111000

This is the key idea behind all of deep learning: stacking layers lets a network build complex shapes out of simple straight lines. But there was one big problem left, which took until the 1980s to solve.

2.6From the perceptron to the modern neuron

If hidden layers solve XOR, why did it take so long? Because nobody knew how to train the hidden layers. The perceptron rule only works for a single neuron, where we can see its error directly. For a hidden neuron, what's the "correct answer"? Nobody tells us.

The answer (backpropagation, Module 5) needs a way to measure how a small change in a weight changes the output. The step function makes that impossible:

Left: the step function jumps suddenly from 0 to 1 at zero and is flat everywhere else. Right: the sigmoid function rises smoothly from 0 to 1.Step function (perceptron)100Sigmoid (modern neurons)100Flat everywhere: no hint which way to moveSmooth slope: gradient descent can follow it
Figure 4. The step function is flat everywhere, with one sudden jump. A tiny change to a weight usually changes nothing at all, so there's no signal telling us which way to move. A smooth function like the sigmoid always gives a slope to follow.

So modern networks replace the step function with smooth activation functions. You'll meet the most important ones in the next module.

Perceptron (1958)Modern artificial neuron
ActivationStep: output is 0 or 1Smooth: sigmoid, tanh, ReLU…
OutputA hard yes/noA number, such as a probability
LearningPerceptron rule: only on mistakesGradient descent and backpropagation: on every example
LayersOnly one neuron can learnMany layers, all trained together
BoundaryOne straight lineAny shape, with enough neurons and layers

2.7Building a perceptron in Python

A perceptron is simple enough to build from scratch in about 20 lines of Python, using NumPy. We'll teach it the AND, OR and XOR rules, then try scikit-learn's built-in Perceptron on a real dataset.

perceptron.py
import numpy as np

# 1. A perceptron built from scratch
class Perceptron:
    def __init__(self, learning_rate=0.1, epochs=20):
        self.lr = learning_rate
        self.epochs = epochs

    def predict(self, X):
        total = X @ self.w + self.b                 # weighted sum + bias
        return np.where(total >= 0, 1, 0)           # step activation

    def fit(self, X, y):
        self.w = np.zeros(X.shape[1])               # start with all weights at 0
        self.b = 0.0
        for epoch in range(self.epochs):
            mistakes = 0
            for xi, target in zip(X, y):
                error = target - self.predict(xi)   # +1, 0 or -1
                self.w += self.lr * error * xi      # the perceptron learning rule
                self.b += self.lr * error
                mistakes += int(error != 0)
            if mistakes == 0:                       # everything correct: stop
                return epoch + 1
        return self.epochs

# 2. Teach it three logic gates
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
gates = {"AND": [0, 0, 0, 1], "OR": [0, 1, 1, 1], "XOR": [0, 1, 1, 0]}
for name, y in gates.items():
    p = Perceptron()
    epochs = p.fit(X, np.array(y))
    correct = (p.predict(X) == y).sum()
    print(f"{name:3}: {correct}/4 correct after {epochs} epochs, "
          f"weights={p.w.round(2)}, bias={p.b:.2f}")

# 3. scikit-learn's Perceptron on a real medical dataset
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import Perceptron as SkPerceptron

X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.25, random_state=42, stratify=y)
model = Pipeline([("scale", StandardScaler()),
                  ("perceptron", SkPerceptron(random_state=42))])
model.fit(X_train, y_train)
print(f"\nBreast cancer data (30 features): test accuracy = {model.score(X_test, y_test):.3f}")
Output
AND: 4/4 correct after 4 epochs, weights=[0.2 0.1], bias=-0.20
OR : 4/4 correct after 4 epochs, weights=[0.1 0.1], bias=-0.10
XOR: 2/4 correct after 20 epochs, weights=[-0.1  0. ], bias=0.00

Breast cancer data (30 features): test accuracy = 0.965

What the output tells us

  • AND and OR are learned perfectly in just 4 epochs, starting from weights of zero.
  • XOR fails. After all 20 epochs, it still only gets 2 of the 4 right. It will never do better, because no straight line can separate XOR.
  • On real data, a single perceptron can do very well: 96.5% on the breast cancer dataset you may know from the Machine Learning track. Many real problems are close to straight-line separable once you have enough features.
  • X @ self.w is NumPy's way of writing the weighted sum: it multiplies each input by its weight and adds them up in one step.

Try this yourself

Change the learning rate to 1.0 and see if AND and OR still learn. Then add a third input column and invent your own rule, such as "1 if at least two of the three inputs are 1". Can the perceptron learn it?

SummaryKey takeaways

  • The perceptron (Rosenblatt, 1958) is a single neuron with a step function: it outputs 1 if the weighted total plus bias is 0 or more, otherwise 0.
  • Weights say how much each input matters; the bias says how easy it is to say yes.
  • The perceptron learning rule: weight = weight + learning rate × error × input. It only changes on mistakes.
  • A perceptron draws a straight-line boundary: weights set the angle, bias shifts it.
  • If the classes can be split by a line, the perceptron is guaranteed to find one.
  • It can't learn XOR, which helped cause the first AI winter. Hidden layers solve it.
  • Modern neurons use smooth activations so that all layers can be trained with gradient descent.

Check your understanding

Your neural networks roadmap

  1. 01
    Introduction to Neural NetworksWhat neural networks are and how they work
  2. 02
    The Perceptron and the Artificial NeuronYou are here
  3. 03
    Activation FunctionsSigmoid, tanh, ReLU and softmax
  4. 04
    Loss Functions and Gradient DescentHow networks measure and reduce error
  5. 05
    BackpropagationHow every weight learns its share of the blame
  6. 06
    Building Networks with KerasYour first deep learning library
  7. 07
    Training Better NetworksOverfitting, dropout, batch normalisation, early stopping
  8. 08
    Convolutional Neural NetworksTeaching computers to see
  9. 09
    Recurrent Neural Networks and LSTMsWorking with sequences
  10. 10
    Transformers and AttentionThe architecture behind ChatGPT and Claude
  11. 11
    Transfer Learning and Pretrained ModelsStanding on the shoulders of giants
  12. 12
    Capstone ProjectBuild and present a deep learning project