TAI BUI
Back to curriculum
BuildPython

The Perceptron

The perceptron is the atom of neural networks. Split it open: weights, a bias, one decision.

TIME: ~60 minutesPREREQUISITES: Phase 1 (Linear Algebra Intuition)

Learning Objectives

  • Implement a perceptron from scratch in Python, including the weight update rule and step activation function
  • Explain why a single perceptron can only solve linearly separable problems and demonstrate the XOR failure case
  • Construct a multi-layer perceptron by composing OR, NAND, and AND gates to solve XOR
  • Train a two-layer network with sigmoid activation and backpropagation to learn XOR automatically

The Problem

You know vectors and dot products. You know that a matrix transforms inputs into outputs. But how does a machine learn which transformation to use?

The perceptron answers this. It's the simplest possible learning machine: take some inputs, multiply by weights, add a bias, and make a binary decision. Then adjust. That's it. Every neural network ever built is layers of this idea stacked together.

Understanding the perceptron means understanding what "learning" actually means in code: adjusting numbers until the output matches reality.

Warm-up0/3
1. You want to combine three numeric signals about a job candidate (test score, interview score, years of experience) into one yes/no decision, giving each signal a different level of importance. What kind of calculation would naturally do that?Warm-up
Three boxes labelled test score, interview score and years of experience, each a number, with arrows into one box labelled yes / no, the one decision.
2. What is the dot product of the vectors [2, 3] and [4, 1]?Warm-up
Two rows of boxes: a = [2, 3] and b = [4, 1], entries lined up by position 1 and 2 with dashed links between the matching entries, and the label a dot b equals question mark.
3. Which Boolean operation outputs true when at least one of its two inputs is true?Warm-up
A table of the four combinations of two inputs A and B (false/true) with the required output column: false for false-false, true for the other three combinations.

The Concept

One Neuron, One Decision

A perceptron takes n inputs, multiplies each by a weight, sums them up, adds a bias, and passes the result through an activation function.

In code, that's a dot product plus a constant:

python
weighted_sum = sum(w * x for w, x in zip(weights, inputs)) + bias
output = 1 if weighted_sum >= 0 else 0

Mermaid diagram

The step function is brutal: if the weighted sum plus bias is >= 0, output 1. Otherwise, output 0.

step(z) = 1  if z >= 0
           0  if z < 0

This is a linear classifier. The weights and bias define a line (or hyperplane in higher dimensions) that splits the input space into two regions.

Analogy: think of it as a bouncer working a strict guest list. Your name on the list, how you're dressed, who you showed up with, each counts for a different amount, and the bouncer adds it all up in their head. Clear the threshold (the bias) and you're in. Fall short and you're turned away. No partial credit, no maybe pile, just a yes or a no.

That weighted-sum-plus-bias computation shows up everywhere once you know to look for it:

  • Every fully connected layer in a modern network, right before the activation gets applied
  • Logistic regression's decision score: the same perceptron, with sigmoid swapped in for the step function
  • A linear SVM's decision function, the sign of w·x + b
  • The output neuron of any binary classifier, whatever architecture feeds into it

The Decision Boundary

For two inputs, the perceptron draws a line through 2D space:

  x2
  ┤
  │  Class 1        /
  │    (0)          /
  │                /
  │               / w1·x1 + w2·x2 + b = 0
  │              /
  │             /     Class 2
  │            /        (1)
  ┼───────────/──────────── x1

Everything on one side of the line outputs 0, while everything on the other outputs 1. Training moves this line until it correctly separates the classes.

The Learning Rule

The perceptron learning rule is simple:

For each training example (x, y_true):
    y_pred = predict(x)
    error = y_true - y_pred

    For each weight:
        w_i = w_i + learning_rate * error * x_i
    bias = bias + learning_rate * error

Get the prediction right and error is zero, so nothing moves. Predict 0 when the answer is 1, and the weights climb. Predict 1 when the answer is 0, and they fall. The learning rate sets how big each step is.

Analogy: it's a thermostat that only ever nudges, never jumps. Miss high and it turns the dial down a notch. Miss low and it turns the dial up a notch. Hit the target and it leaves the dial alone. Run that nudge over enough examples and the dial settles wherever the room actually needs it.

The XOR Problem

Here's where it breaks. Look at these logic gates:

AND gate:           OR gate:            XOR gate:
x1  x2  out         x1  x2  out         x1  x2  out
0   0   0           0   0   0           0   0   0
0   1   0           0   1   1           0   1   1
1   0   0           1   0   1           1   0   1
1   1   1           1   1   1           1   1   0

AND and OR are linearly separable: you can draw a single line to separate the 0s from the 1s. XOR is not. No single line can separate [0,1] and [1,0] from [0,0] and [1,1].

AND (separable):        XOR (not separable):

  x2                      x2
  1 ┤  0     1            1 ┤  1     0
    │     /                 │
  0 ┤  0 / 0              0 ┤  0     1
    ┼──/──────── x1         ┼──────────── x1
       line works!          no single line works!

This is a fundamental limit. A single perceptron can only solve linearly separable problems. Minsky and Papert proved this in 1969 and it nearly killed neural network research for a decade.

The fix: stack perceptrons into layers. A multi-layer perceptron can solve XOR by combining two linear decisions into a nonlinear one.

Check: The Concept0/18
1. What is a perceptron?Define
A neuron diagram: inputs x1 = 1 and x2 = 0 with weights 1.0 and 1.0 feed a sum node with bias -0.5 giving z = 0.5, then a box showing a jump from 0 to 1 at zero, and an output of 1.
The OR neuron from xor_network, values computed by running it.
2. What does a weight do in a perceptron?Define
A neuron diagram for the trained AND perceptron: inputs x1 = 1 and x2 = 1 with weights 0.2 and 0.1 highlighted on the arrows, bias -0.2, sum z = 0.1, a jump-from-0-to-1 box and output 1.
Weights and bias from running the lesson's AND training.
3. What is the role of the bias in a perceptron?Define
A table for the NAND neuron with weights -1 and -1 and bias 1.5: for each of the four inputs it lists the weighted part, the bias column (outlined, always 1.5), the sum z and the output.
4. What does an activation function do in a neuron?Define
A neuron diagram for the NAND neuron with inputs 1 and 1, weights -1.0 and -1.0, bias 1.5, sum z = -0.5, then a highlighted box labelled activation and an output marked with a question mark.
5. What does 'linearly separable' mean for a classification problem?Define
Two scatter plots on the unit square with the corners (0,0), (0,1), (1,0), (1,1) labelled 0 or 1: the AND dataset (only (1,1) is 1) and the XOR dataset ((0,1) and (1,0) are 1), no lines drawn.
Class labels are the lesson's and_data and xor_data.
6. In the perceptron's decision boundary equation w*x + b = 0, what does this equation represent geometrically for two inputs?Define
A unit-square plot with the four inputs of the OR neuron labelled with their sums z = -0.5, 0.5, 0.5 and 1.5, above the equation 1.0*x1 + 1.0*x2 - 0.5 = 0; no boundary is drawn.
Sums computed from the lesson's OR neuron.
7. What does the XOR problem demonstrate?Define
A truth table for XOR (0,0 -> 0; 0,1 -> 1; 1,0 -> 1; 1,1 -> 0) beside a unit-square plot of the same four points labelled with their outputs, no line drawn.
8. What is a multi-layer perceptron?Define
A network diagram of xor_network: inputs x1 and x2 feed two neurons OR (weights 1, 1, bias -0.5) and NAND (weights -1, -1, bias 1.5), whose outputs feed one AND neuron (weights 1, 1, bias -1.5).
Weights typed in the lesson's xor_network.
9. In the perceptron learning rule, what happens when the prediction matches the target?Explain
A snapshot of the perceptron in epoch 3 of AND training (weights [0.2, 0.1], bias -0.1, learning rate 0.1) on the example inputs [0, 0] with target 0 and prediction 0, above the update code from the lesson.
State taken from a real run of the lesson's Perceptron; code copied from the lesson.
10. Why can one perceptron learn AND but not XOR?Explain
Two truth tables over the same four inputs: AND with outputs 0, 0, 0, 1 and XOR with outputs 0, 1, 1, 0.
Data are the lesson's and_data and xor_data.
11. What does the learning rate control in the perceptron update rule?Explain
A fresh Perceptron(2) with weights [0.0, 0.0] and bias 0.0 sees the example ([0, 1], 0), predicts 1 so the error is -1; the two update lines using self.lr are shown and the new weights are marked with a question mark.
Code copied from the lesson.
12. A perceptron predicts 0 for an example whose true label is 1. In which direction does the update push the weights on the active inputs?Explain
A perceptron mid-training with weights [0.0, 0.0], bias -0.1, example inputs [1, 1], target 1 and prediction 0, and a number line showing the weighted sum z = -0.1 just left of the threshold 0.
State from a real run of the lesson's Perceptron on and_data.
13. What does stacking perceptrons into layers add over a single perceptron?Explain
Two diagrams: on the left inputs x1 and x2 feed a single perceptron P that gives one output; on the right they feed a layer of two perceptrons whose outputs feed a third perceptron, which gives the output. Under them: 1 neuron with 3 numbers (2 weights, 1 bias) and 3 neurons with 9 numbers (6 weights, 3 biases).
14. How does logistic regression's decision score relate to a perceptron?Explain
Two rows of boxes for the same input (1, 0): the perceptron row goes x, then z = w*x + b = 0.5, then step, then 0 or 1; the logistic regression row goes x, then a highlighted decision score box, then a question mark box, then probability.
15. You train a single perceptron for 10,000 epochs on a dataset shaped exactly like XOR, and the error never reaches zero. What is the most likely explanation?Analyze
A line plot of the number of mistakes per epoch for the first 40 epochs of a single perceptron trained on XOR: 3 mistakes in epochs 1 and 2, then 4 every epoch, never reaching 0; a note says that over all 10,000 epochs the fewest was 3 and the most was 4.
Real run of the lesson's Perceptron class logic on xor_data (learning rate 0.1, zero start).
16. After seeing a single perceptron fail on XOR, a colleague concludes that neural networks cannot learn nonlinear patterns. What is wrong with that reasoning?Analyze
Terminal output of the single perceptron on XOR (did not converge after 1000 epochs, two of four predictions wrong) above a speech box where a colleague concludes that neural networks cannot learn nonlinear patterns.
Terminal text is real output of the lesson's code.
17. You want a binary classifier that gives a graded confidence instead of a hard 0 or 1, while keeping the perceptron's weighted sum. What change fits?Design
A plot of the OR neuron's output against its sum z from -2.5 to 2.5: output 0 for z below 0 and 1 from 0 up, with the four inputs marked at z = -0.5, 0.5, 0.5 and 1.5; a note says a graded confidence is wanted instead.
Sums computed from the lesson's OR neuron.
18. Before choosing an architecture for a new two-feature binary problem, which check tells you whether a single perceptron could work?Design
A scatter plot of two features with ten points of class A and ten of class B, drawn on axes from -0.1 to 1.1.
Illustrative data generated with a seeded random generator, not from the lesson.

Build It

Step 1: The Perceptron class

python
class Perceptron:
    def __init__(self, n_inputs, learning_rate=0.1):
        self.weights = [0.0] * n_inputs
        self.bias = 0.0
        self.lr = learning_rate
 
    def predict(self, inputs):
        total = sum(w * x for w, x in zip(self.weights, inputs))
        total += self.bias
        return 1 if total >= 0 else 0
 
    def train(self, training_data, epochs=100):
        for epoch in range(epochs):
            errors = 0
            for inputs, target in training_data:
                prediction = self.predict(inputs)
                error = target - prediction
                if error != 0:
                    errors += 1
                    for i in range(len(self.weights)):
                        self.weights[i] += self.lr * error * inputs[i]
                    self.bias += self.lr * error
            if errors == 0:
                print(f"Converged at epoch {epoch + 1}")
                return
        print(f"Did not converge after {epochs} epochs")

Step 2: Train on logic gates

python
and_data = [
    ([0, 0], 0),
    ([0, 1], 0),
    ([1, 0], 0),
    ([1, 1], 1),
]
 
or_data = [
    ([0, 0], 0),
    ([0, 1], 1),
    ([1, 0], 1),
    ([1, 1], 1),
]
 
not_data = [
    ([0], 1),
    ([1], 0),
]
 
print("=== AND Gate ===")
p_and = Perceptron(2)
p_and.train(and_data)
for inputs, _ in and_data:
    print(f"  {inputs} -> {p_and.predict(inputs)}")
 
print("\n=== OR Gate ===")
p_or = Perceptron(2)
p_or.train(or_data)
for inputs, _ in or_data:
    print(f"  {inputs} -> {p_or.predict(inputs)}")
 
print("\n=== NOT Gate ===")
p_not = Perceptron(1)
p_not.train(not_data)
for inputs, _ in not_data:
    print(f"  {inputs} -> {p_not.predict(inputs)}")

Step 3: Watch XOR fail

python
xor_data = [
    ([0, 0], 0),
    ([0, 1], 1),
    ([1, 0], 1),
    ([1, 1], 0),
]
 
print("\n=== XOR Gate (single perceptron) ===")
p_xor = Perceptron(2)
p_xor.train(xor_data, epochs=1000)
for inputs, expected in xor_data:
    result = p_xor.predict(inputs)
    status = "OK" if result == expected else "WRONG"
    print(f"  {inputs} -> {result} (expected {expected}) {status}")

It will never converge. This is the hard proof that a single perceptron cannot learn XOR.

Step 4: Solve XOR with two layers

The trick: XOR = (x1 OR x2) AND NOT (x1 AND x2). Combine three perceptrons:

Mermaid diagram

python
def xor_network(x1, x2):
    or_neuron = Perceptron(2)
    or_neuron.weights = [1.0, 1.0]
    or_neuron.bias = -0.5
 
    nand_neuron = Perceptron(2)
    nand_neuron.weights = [-1.0, -1.0]
    nand_neuron.bias = 1.5
 
    and_neuron = Perceptron(2)
    and_neuron.weights = [1.0, 1.0]
    and_neuron.bias = -1.5
 
    hidden1 = or_neuron.predict([x1, x2])
    hidden2 = nand_neuron.predict([x1, x2])
    output = and_neuron.predict([hidden1, hidden2])
    return output
 
 
print("\n=== XOR Gate (multi-layer network) ===")
for inputs, expected in xor_data:
    result = xor_network(inputs[0], inputs[1])
    print(f"  {inputs} -> {result} (expected {expected})")

All four cases correct. Stacking perceptrons into layers creates decision boundaries that no single perceptron can produce.

Step 5: Train a Two-Layer Network

Step 4 hand-wired the weights. That works for XOR, but not for real problems where you don't know the right weights in advance. So swap the activation: replace the step function with sigmoid, and learn the weights automatically through backpropagation.

python
class TwoLayerNetwork:
    def __init__(self, learning_rate=0.5):
        import random
        random.seed(0)
        self.w_hidden = [[random.uniform(-1, 1), random.uniform(-1, 1)] for _ in range(2)]
        self.b_hidden = [random.uniform(-1, 1), random.uniform(-1, 1)]
        self.w_output = [random.uniform(-1, 1), random.uniform(-1, 1)]
        self.b_output = random.uniform(-1, 1)
        self.lr = learning_rate
 
    def sigmoid(self, x):
        import math
        x = max(-500, min(500, x))
        return 1.0 / (1.0 + math.exp(-x))
 
    def forward(self, inputs):
        self.inputs = inputs
        self.hidden_outputs = []
        for i in range(2):
            z = sum(w * x for w, x in zip(self.w_hidden[i], inputs)) + self.b_hidden[i]
            self.hidden_outputs.append(self.sigmoid(z))
        z_out = sum(w * h for w, h in zip(self.w_output, self.hidden_outputs)) + self.b_output
        self.output = self.sigmoid(z_out)
        return self.output
 
    def train(self, training_data, epochs=10000):
        for epoch in range(epochs):
            total_error = 0
            for inputs, target in training_data:
                output = self.forward(inputs)
                error = target - output
                total_error += error ** 2
 
                d_output = error * output * (1 - output)
 
                saved_w_output = self.w_output[:]
                hidden_deltas = []
                for i in range(2):
                    h = self.hidden_outputs[i]
                    hd = d_output * saved_w_output[i] * h * (1 - h)
                    hidden_deltas.append(hd)
 
                for i in range(2):
                    self.w_output[i] += self.lr * d_output * self.hidden_outputs[i]
                self.b_output += self.lr * d_output
 
                for i in range(2):
                    for j in range(len(inputs)):
                        self.w_hidden[i][j] += self.lr * hidden_deltas[i] * inputs[j]
                    self.b_hidden[i] += self.lr * hidden_deltas[i]
python
net = TwoLayerNetwork(learning_rate=2.0)
net.train(xor_data, epochs=10000)
for inputs, expected in xor_data:
    result = net.forward(inputs)
    predicted = 1 if result >= 0.5 else 0
    print(f"  {inputs} -> {result:.4f} (rounded: {predicted}, expected {expected})")

Two key differences from Step 4. First, sigmoid replaces the step function: it's smooth, so gradients exist. Second, the train method propagates error backward from output to hidden layer, adjusting every weight proportionally to its contribution to the error. That's backpropagation in 20 lines.

This is the bridge to Lesson 03. The math behind d_output and hidden_deltas is the chain rule applied to the network graph. We'll derive it properly there.

Check: Build It0/13
1. How is XOR solved using multiple perceptrons?Explain
A table with columns x1, x2, h1, h2 and out for the four inputs: out is the XOR column 0, 1, 1, 0 while h1 and h2 are question marks.
2. Why does the two-layer network use sigmoid instead of the step function?Explain
Two small plots of output against the weighted sum z from -6 to 6: step jumps from 0 to 1 at z = 0, sigmoid rises smoothly from near 0 to near 1; below them a note that TwoLayerNetwork uses the sigmoid where Perceptron.predict uses the step.
Curves computed from the lesson's step and sigmoid functions.
3. What two changes let the two-layer network learn XOR automatically instead of relying on hand-tuned weights?Explain
Three cards: the weights typed in the Step 4 xor_network, the random starting values of TwoLayerNetwork (seed 0), and the same values after 10,000 epochs of training on XOR.
Values from running the lesson's code; the Step 4 numbers are typed in the lesson.
4. Using the hand-wired weights in xor_network, what happens for input (1, 1)?Apply
The xor_network diagram with inputs x1 = 1 and x2 = 1: OR (weights 1, 1, bias -0.5), NAND (weights -1, -1, bias 1.5) and AND (weights 1, 1, bias -1.5); every neuron's output is marked with a question mark.
Weights typed in the lesson's xor_network.
5. Using the hand-wired weights in xor_network, what do the OR and NAND hidden neurons output for input (0, 0), and what is the final output?Apply
The xor_network diagram with inputs x1 = 0 and x2 = 0: OR (weights 1, 1, bias -0.5), NAND (weights -1, -1, bias 1.5) and AND (weights 1, 1, bias -1.5); every neuron's output is marked with a question mark.
Weights typed in the lesson's xor_network.
6. A fresh Perceptron(2) with learning_rate 0.1 starts training on the AND data. After it processes the first example ([0, 0], 0), what are its weights and bias?Apply
A fresh Perceptron(2) with weights [0.0, 0.0] and bias 0.0 about to process the first AND example (inputs [0, 0], target 0), with the predict and update lines from the lesson listed below.
Code copied from the lesson.
7. The single perceptron runs p_xor.train(xor_data, epochs=1000). What does the training method print when it finishes?Apply
The call p_xor.train(xor_data, epochs=1000) and, from the train method, the errors == 0 check that prints Converged at epoch and returns, followed by the final print line after the loop; xor_data is listed below.
Code copied from the lesson.
8. In TwoLayerNetwork.train, the network outputs 0.5 and the target is 1. What value does d_output take?Apply
A card with output = 0.5 and target = 1, and the two lines from TwoLayerNetwork.train: error = target - output and d_output = error * output * (1 - output), with d_output marked as a question mark.
Code copied from the lesson.
9. How many trainable numbers (weights plus biases) does TwoLayerNetwork hold?Apply
The five attribute assignments from TwoLayerNetwork.__init__: w_hidden as two lists of two random numbers, b_hidden two numbers, w_output two numbers, b_output one number and lr.
Code copied from the lesson.
10. A student's xor_network passes the raw inputs [x1, x2] to the AND neuron instead of the OR and NAND outputs, and the XOR results are wrong. Why?Analyze
Two code cards: the lesson's last three lines of xor_network and the student's version where the AND neuron receives [x1, x2] instead of [hidden1, hidden2], and a table of the student's outputs 0, 0, 0, 1 against the expected XOR outputs 0, 1, 1, 0.
Code from the lesson with the student's change; outputs computed by running the AND neuron.
11. A student keeps the backpropagation code but swaps sigmoid back to the step function in TwoLayerNetwork, and the XOR error stops improving. What is the likely cause?Analyze
Two error curves over 10,000 epochs of TwoLayerNetwork training on XOR: with sigmoid the total squared error falls from 1.2164 to 0.0003; with the step function swapped in and the backpropagation code kept, it stays flat at 2.0000.
Real runs of the lesson's TwoLayerNetwork (seed 0, learning rate 2.0); the step run only replaces the sigmoid method.
12. How does the hand-wired xor_network differ from TwoLayerNetwork as a way to solve XOR?Analyze
A table of the four XOR inputs with the expected output, the hand-wired xor_network output (0, 1, 1, 0) and the trained TwoLayerNetwork output (0.0074, 0.9923, 0.9923, 0.0094).
Outputs from running the lesson's code.
13. You must classify points whose positive class sits on two opposite corners of a square, and you want the weights learned rather than hand-picked. Which design fits?Design
A square with a positive point on two opposite corners (top-left and bottom-right) and a negative point on the other two corners.

Use It

Everything you just built from scratch exists in one import:

python
from sklearn.linear_model import Perceptron as SkPerceptron
import numpy as np
 
X = np.array([[0,0],[0,1],[1,0],[1,1]])
y = np.array([0, 0, 0, 1])
 
clf = SkPerceptron(max_iter=100, tol=1e-3)
clf.fit(X, y)
print([clf.predict([x])[0] for x in X])

Five lines. Your 30-line Perceptron class does the same thing. The sklearn version adds convergence checks, multiple loss functions, and sparse input support, but the core loop is identical: weighted sum, step function, weight update on error.

The real gap shows up at scale. What changes in production networks:

  • The step function becomes sigmoid, ReLU, or other smooth activations
  • Weights are learned automatically via backpropagation (Lesson 03)
  • Layers get deeper: 3, 10, 100+ layers
  • The same principle holds: each layer creates new features from the previous layer's outputs

A single perceptron can only draw straight lines. Stack them, and you can draw any shape.

Check: Use It0/3
1. How does scikit-learn's Perceptron class relate to the from-scratch Perceptron class built earlier in the lesson?Explain
Two cards of results on the AND data: the lesson's Perceptron class (converged at epoch 4, weights [0.2, 0.1], bias -0.2, predictions [0, 0, 0, 1]) and scikit-learn's Perceptron (coef_ [2.0, 2.0], intercept_ [-2.0], n_iter_ 10, predictions [0, 0, 0, 1]).
Real runs. random_state=0 was added to the sklearn call so the numbers are reproducible; 30 different seeds all gave [0, 0, 0, 1].
2. You've hand-wired weights for a small XOR network, but now need it to handle real data at scale. What actually has to change?Explain
Two panels joined by an arrow: your small XOR network (2 inputs, 3 neurons, 9 numbers typed by hand, listed as the OR, NAND and AND weights and biases, 4 examples) and real data at scale (many more inputs, many more examples, patterns nobody wrote down).
3. Assuming it converges, what predictions does the sklearn snippet produce for the four AND inputs, in order, after fitting on y = [0, 0, 0, 1]?Apply
The five lines of the scikit-learn snippet: X is the four AND inputs, y is [0, 0, 0, 1], a Perceptron with max_iter=100 and tol=1e-3 is fitted, and a list comprehension of predictions is printed; the printed list is a question mark.
Code copied from the lesson.

Ship It

This lesson produces:

  • outputs/skill-perceptron.md, a skill covering when to reach for a single-layer perceptron versus a multi-layer network
Author's Note

The XOR failure is worth sitting with longer than most tutorials give it credit for. Minsky and Papert weren't wrong about the math: a single perceptron genuinely cannot solve XOR, full stop. What they got wrong, and what a decade of funding cuts got wrong along with them, was mistaking a limit of one architecture for a limit of the whole idea. Stack two of them and the limit disappears. I think about that every time someone declares a current architecture 'fundamentally incapable' of something. Sometimes that's true. Often it just means nobody found the right way to stack it yet.

The other thing worth doing here, even if you already know backprop cold: type out Step 5 by hand once. Autograd in PyTorch hides d_output and hidden_deltas behind a single call to .backward(). That's the right way to write production code. But skip writing those lines yourself even once, and .backward() stays a black box you trust instead of a shortcut for math you already understand.

Exercises

  1. Train a perceptron on a NAND gate (the universal gate: any logic circuit can be built from NAND). Verify its weights and bias form a valid decision boundary.
  2. Modify the Perceptron class to track the decision boundary (w1x1 + w2x2 + b = 0) at each epoch. Print how the line shifts during training on the AND gate.
  3. Build a 3-input perceptron that outputs 1 only when at least 2 of the 3 inputs are 1 (a majority vote function). Is this linearly separable? Why?

Key Terms

TermWhat people sayWhat it actually means
Perceptron"A fake neuron"A linear classifier: dot product of inputs and weights, plus bias, through a step function
Weight"How important an input is"A multiplier that scales each input's contribution to the decision
Bias"The threshold"A constant that shifts the decision boundary, letting the perceptron fire even with zero inputs
Activation function"The thing that squishes values"A function applied after the weighted sum: step function for perceptrons, sigmoid/ReLU for modern networks
Linearly separable"You can draw a line between them"A dataset where a single hyperplane can perfectly separate the classes
XOR problem"The thing perceptrons can't do"Proof that single-layer networks cannot learn non-linearly-separable functions
Decision boundary"Where the classifier switches"The hyperplane w*x + b = 0 that divides input space into two classes
Multi-layer perceptron"A real neural network"Perceptrons stacked in layers, where each layer's output feeds the next layer's input

Further Reading

  • Frank Rosenblatt, "The Perceptron: A Probabilistic Model for Information Storage and Organization in the Brain" (1958) — the original paper that started it all
  • Minsky & Papert, "Perceptrons" (1969) — the book that proved XOR was unsolvable by single-layer networks and killed perceptron research for a decade
  • Michael Nielsen, "Neural Networks and Deep Learning", Chapter 1 (http://neuralnetworksanddeeplearning.com/) — free online, best visual explanation of how perceptrons compose into networks

Code

Ships With