Perceptron Learning and Introduction to Regression
Prerequisite Knowledge
This lecture builds on the following concepts from earlier lectures. If any feel unfamiliar, review the linked notes before proceeding.
Previously Covered in This Subject
- Perceptron (artificial neuron) model — covered in Lecture 2
- Thresholding and activation functions — covered in Lecture 2
- Multi-layer perceptrons — covered in Lecture 2
Perceptron Learning and Introduction to Regression
3.1 Perceptron Mathematical Model
3.1.1 Hook
Can a machine learn to make a yes/no decision on its own? The perceptron — invented in 1948 — was the first device to do exactly that. It weighs evidence, adds it up, and says yes or no.
3.1.2 Intuition and Analogy
Picture a judge in a courtroom. Witnesses give testimony (inputs). Some witnesses are more reliable than others (weights). The judge listens to everyone, weighs their credibility, and sums up the evidence. If the total crosses a threshold, the judge says "guilty." If not, "not guilty."
A perceptron is that judge. It takes numbers as input. It multiplies each by a weight — how much it trusts that input. Then it adds them all up and checks the total against a threshold.
Where the analogy breaks: The judge uses experience and reasoning. The perceptron uses pure math. And unlike the judge, the perceptron can adjust its weights by learning from mistakes.
3.1.3 Formalize — The Mathematical Model
A perceptron receives input features. They are . Each feature has a weight . The weight says how important that feature is. There is also a bias . The bias is an extra offset that shifts the decision boundary.
First, the perceptron computes a weighted sum:
Some textbooks write instead of and set a dummy input . Then the sum becomes compact:
Second, the perceptron applies a threshold. It compares to zero:
The original perceptron used and instead of and :
Both conventions are fine. The key idea does not change.
A linear threshold unit (LTU) combines a weighted sum with a threshold function. That is the core of a perceptron. The threshold here is linear — it compares against zero. Later, you will see nonlinear ones called activation functions.
3.1.4 Symbol Registry
| Symbol | Meaning | LaTeX | Type | Domain |
|---|---|---|---|---|
| i-th input feature | scalar | |||
| weight for i-th feature | scalar | |||
| bias term (also written ) | scalar | |||
| number of features | scalar | |||
| predicted output | scalar | or | ||
| or | target (actual) output | scalar | or | |
| weighted sum (pre-activation) | scalar |
3.1.5 Worked Example — A Tiny Perceptron
Say a perceptron has two features with weights and , and bias . For input :
- Weighted sum:
- Since , the threshold gives .
For input :
- Since , .
Final outputs: (2,4) → 0, (4,1) → 1. The second input gave a stronger positive sum, so the perceptron decided differently.
3.1.6 Assumptions and Scope
Assumption 1 — Linear separability. A single perceptron can only classify data that is linearly separable. It fails if a straight line cannot split the classes. If the data is not linearly separable — like the XOR problem — one perceptron will fail.
Assumption 2 — Binary classification. The perceptron outputs one of two labels. It cannot handle multiple classes directly (though multiple perceptrons working together can).
Scope: The perceptron is a building block. Real neural networks stack thousands of perceptrons in layers. The single-unit model here is only the starting point.
3.1.7 Visual Intuition
Imagine a 2D scatter plot. The X-axis is feature , the Y-axis is feature . Data points are either circles (class 0) or crosses (class 1). The perceptron draws a straight line through this plane: . Everything on one side of the line is class 1. Everything on the other side is class 0. The weights determine the angle and position of the line. The bias slides it left or right. Learning means rotating and shifting this line until it splits the circles from the crosses perfectly.
3.1.8 Pitfalls
- Confusing bias with threshold. The bias is part of the weighted sum. The threshold is the comparison against zero (or another value) after the sum. The bias shifts the line. The threshold makes the decision.
- Forgetting the dummy input. When using the compact form , remember that always. The bias is . This trick lets you fold the bias into the sum.
- Thinking 1/0 and +1/–1 are different models. They are the same perceptron with a shifted convention. The math works the same way.
3.1.9 Student Questions and Answers
Q: Is threshold and activation function the same thing?
A: Yes. Right now you see a simple threshold — compare against zero. Later, you will meet other activation functions like sigmoid, ReLU, and tanh. They are all threshold systems, just with different shapes.
Q: Can bias be zero?
A: Yes. The bias is a learnable parameter just like the weights. It can be zero, positive, or negative. During training, the algorithm adjusts it to whatever value works best.
3.1.10 Recap and Bridge
A perceptron takes weighted inputs, sums them with a bias, and decides yes or no by comparing the sum against zero. It is the simplest classifier — one straight line dividing the data world into two halves.
Now that you know what a perceptron is, you will see how to pick the right weights to mimic logic gates.
3.1.11 Real-World and Domain Connection
The perceptron was the first hardware implementation of a learning machine. Frank Rosenblatt built it at Cornell in the late 1950s as the "Mark I Perceptron." It was a room-sized machine with 400 photocells connected to neurons via potentiometers (adjustable weights). It could recognize simple patterns like letters. While primitive by today's standards, it proved that machines could learn from data. Modern spam filters, credit card fraud detectors, and medical screening tools all descend from this yes/no decision unit.
3.2 Designing Logic Gates with a Single Perceptron
3.2.1 Hook
What if a single neuron could act like an AND gate — outputting 1 only when both inputs are 1? It turns out you can hand-pick the weights of a perceptron to mimic any simple Boolean logic gate.
3.2.2 Intuition and Analogy
Think of a bouncer at a club. He enforces two rules: "Must have ID" AND "Must be over 21." Both must be true to get in. This is the AND gate. The bouncer makes a call based on two binary checks.
The perceptron does the same. It takes two binary inputs and produces one binary output. By setting the weights and bias just right, you make the perceptron behave like an AND gate. It fires only when both inputs are 1.
Where the analogy breaks: The bouncer uses clear rules. The perceptron encodes the rule as numbers (weights). The math is the same, just expressed differently.
3.2.3 Formalize — AND Gate Weight Design
Start with the AND gate truth table. Each row is a training example:
| A () | B () | Target |
|---|---|---|
| 0 | 0 | 0 |
| 0 | 1 | 0 |
| 1 | 0 | 0 |
| 1 | 1 | 1 |
The perceptron equation with bias (where ):
Decision rule: if , predict 1; if , predict 0.
Set up the inequalities for each row:
You now have four inequalities and three unknowns (). Many solutions exist. One valid choice: , , .
3.2.4 Worked Example — Verifying the Found Weights
Plug , , into each row:
Row 1 (0,0): → . ✓ (target = 0)
Row 2 (0,1): → . ✓
Row 3 (1,0): → . ✓
Row 4 (1,1): → . ✓
All four rows match. These weights perfectly mimic an AND gate. Sense check: only the (1,1) case produces a positive sum — exactly what AND should do.
3.2.5 Visual Intuition — The Decision Boundary
Plot the four data points on a 2D plane ( on X-axis, on Y-axis):
- (0,0) — label 0
- (0,1) — label 0
- (1,0) — label 0
- (1,1) — label 1 (the only positive case)
Set the weighted sum to zero to get the decision line:
The line cuts through the plane diagonally. The point (1,1) sits above and to the right of the line — so it is classified as 1. The other three points fall below — classified as 0. The line perfectly separates the two classes.
Takeaway: Because the data is linearly separable, one straight line does the job. This is exactly what machine learning tries to do — find patterns intelligently from data.
3.2.6 Assumptions and Scope
Scope — Linear separability is key. AND, OR, and NOT gates are all linearly separable. That is why a single perceptron can solve them. But XOR is not — a point we will explore in Section 3.9.
Scope — Manual weight design vs. learning. This section shows hand-solved weights. Real problems have too many features for hand-solving. The perceptron learning algorithm (Section 3.3) finds weights automatically.
3.2.7 Pitfalls
- Assuming one unique solution. There are infinitely many weight combinations that satisfy the inequalities. works too. All give the same classification.
- Confusing strict () vs. non-strict (). Output-0 rows need strict inequality (). Output-1 rows need non-strict (). Reversing these ruins the gate.
- Thinking only four data points is too few. It is enough for a truth table. But for real data, four examples would not work. You need many examples to learn a reliable pattern.
3.2.8 Student Questions and Answers
Q: How do you determine which side of the line corresponds to which label?
A: Plug the values into the sum . If the result is , label it 1. If , label it 0. The positive side is class 1, the negative side is class 0.
Q: How did we arrive at and ?
A: Solve the four inequalities with three unknowns using linear algebra. In a few minutes, you will see a systematic algorithm. The perceptron learning algorithm finds these weights automatically for any dataset.
Q: Is the OR gate designed the same way?
A: Yes. The procedure is identical. List the OR truth table data points, set up the inequalities, and solve for the weights. One valid solution for OR: , , . Try verifying it yourself.
3.2.9 Recap and Bridge
You can hard-code a perceptron to act as any linearly separable logic gate by solving a system of inequalities. AND, OR, and NOT all work with one neuron.
But solving inequalities by hand does not scale to real data. Next: how to make the perceptron learn weights from examples automatically.
3.2.10 Real-World and Domain Connection
Designing logic gates with perceptrons is more than a classroom exercise. It shows that a neural network can represent Boolean functions — the foundation of all digital computation. In fact, any Boolean function can be built from perceptrons. This requires multiple layers. It is the idea behind the universal approximation theorem. Early AI researchers used perceptrons to model decision-making: if humidity is high AND temperature is above 30°C, trigger irrigation. Modern rule-based expert systems and decision support tools still use this idea. Agriculture, medicine, and industrial control all benefit. But now with learned weights rather than hand-set ones.
3.3 Perceptron Learning Algorithm — Intuition
3.3.1 Hook
Hand-solving inequalities works for four rows of an AND gate. But what if you had 10,000 data points with 50 features? You need an algorithm that finds the right weights on its own — by trial, error, and correction.
3.3.2 Intuition and Analogy
Picture a person learning to throw darts at a bullseye. The first throw misses left. So the person adjusts — aim a bit right. Next throw misses low. Adjust up. Each miss gives feedback, and each adjustment is small. Over many throws, the aim gets closer and closer.
The perceptron learning algorithm does the same. It starts with random weights (random aim). It looks at the data and checks if it classified each point correctly. For every mistake, it tweaks the weights a little bit — in the direction that fixes the mistake. Over many rounds, the decision line shifts until it separates the classes perfectly.
Where the analogy breaks: The dart thrower has one target. The perceptron has many data points and tries to satisfy all of them at once. Sometimes one adjustment fixes one point but breaks another.
3.3.3 Purpose — Why This Algorithm Exists
The perceptron learning algorithm solves this problem. Given labeled training data, find weights and bias that produce correct classifications for all training examples. It is guaranteed to converge — to find a perfect separator — if the data is linearly separable.
3.3.4 Inputs and Outputs
Inputs:
- Training data has pairs. Each pair is . Here is a feature vector and or is the target label.
- Learning rate : a small positive number controlling step size (e.g., 0.01, 0.1).
- Maximum iterations: an optional stopping limit.
Outputs:
- Learned weights and bias (or consolidated as with ).
- The decision boundary: a hyperplane defined by .
3.3.5 Steps — The Algorithm at a Glance
- Initialize: Set all weights to zero (or small random values). Set learning rate .
- Forward pass: For each data point, compute the weighted sum . Apply the threshold to get the prediction .
- Check: Compare with the target . If they match, move to the next point. If they differ, it is a misclassification.
- Update weights: For each misclassified point, adjust every weight:
The bias updates the same way (with ).
- Repeat: Go through all data points again. Keep doing this until one of three things happens. (a) Error reaches zero. (b) Maximum iterations is hit. (c) Error stops improving.
- Output: The final weights define the decision boundary.
3.3.6 Trace — Goa Fruit Classification Walkthrough
Scenario: Classify goa fruits into white pulp (class 0) and pink pulp (class 1). Use two features: texture () and color (). Say you have 10 historical data points with known labels.
Initial state: All weights are zero. The "line" is . This is the line — effectively, it classifies everything as class 1 (since ). Most points will be misclassified.
Iteration 1: The algorithm scans each point. For each pink-pulp fruit wrongly predicted as white, it nudges and up in proportion to the error. For each white-pulp fruit wrongly predicted as pink, it nudges them down. The line rotates slightly.
Iteration 2: The line is now . It separates the clusters better. Only 3 points are misclassified now.
Iteration 5: The error is zero. The line perfectly splits blue (white pulp) from red (pink pulp) points. The algorithm stops.
Final weights: , , . The line is .
3.3.7 Quantifying Error
The weight update depends on how far wrong the prediction is. For a single data point:
If the target is 1 and the prediction is 0: error = +1 (weights should go up). If the target is 0 and the prediction is 1: error = −1 (weights should go down). If they match: error = 0 (no update).
The gradient is the mathematical tool that tells you which direction to adjust each weight. Think of the error as a landscape of hills and valleys. The gradient is the steepest downhill direction. The weight update moves you a small step — of size — in that direction.
When you add up errors across all data points, you get the loss (also called the cost). Minimizing loss is the machine's goal.
3.3.8 Complexity and Cost
A single pass through all data points is one epoch. Each epoch requires operations where is the number of features. For linearly separable data, the algorithm converges. But the number of epochs needed can be large for difficult problems. For non-linearly separable data, the algorithm never converges — it oscillates forever.
3.3.9 When to Use and Alternatives
Use the perceptron algorithm when: the data is known to be linearly separable and you need a simple binary classifier. It is fast and guarantees convergence on separable data.
Do NOT use when: the data is not linearly separable (→ use logistic regression, SVM with kernels, or a multi-layer perceptron). Also avoid it when you need probability outputs (the perceptron gives only hard decisions).
3.3.10 Pitfalls
- Learning rate too big. A large makes the weights jump around — the line might overshoot and never settle. A rate too small makes learning painfully slow. Typical values: 0.01 to 0.5.
- Assuming convergence means good generalization. The algorithm finds a line that separates the training data perfectly. It does not guarantee good performance on new, unseen data.
- Zero initialization. Starting all weights at zero is common for perceptrons. But for deep networks, this prevents learning — you need random initialization.
3.3.11 Student Questions and Answers
Q: How is error calculated?
A: In the goa fruit demo, error was a simple count of misclassifications. More generally, error is the difference per data point. When you combine these errors across all points, you get the loss — a function of the error you try to minimize.
Q: How do we determine the step size (learning rate)?
A: The learning rate is a hyperparameter — a tuning knob you set before training. There is no fixed rule. You try values like 0.1, 0.01, 0.5 and see which works best for your dataset. Parameters that control the algorithm (rather than being learned from data) are called hyperparameters.
Q: Is the target always known?
A: Yes — in supervised learning, which this course covers. The target label comes with the training data. In unsupervised learning (covered in a later course), the target is unknown and the machine must find patterns on its own.
3.3.12 Recap and Bridge
The perceptron learning algorithm starts with random weights. It scans the data. It corrects mistakes by nudging weights in proportion to the error. It repeats until the decision line separates the classes. The learning rate controls the size of each nudge.
Next, you will see this algorithm in action — a full step-by-step worked example on the NOT gate.
3.3.13 Real-World and Domain Connection
The perceptron algorithm was the first practical proof that machines could learn from examples — a milestone in 1958. Today, the same principle of "predict, compare, adjust" powers everything from Netflix recommendations to self-driving car perception. Each time YouTube suggests a video you might like, a variant of this loop runs. The model predicts which videos match your taste. It checks against what you actually watched. Then it updates its internal weights. The perceptron's simple idea — learn from mistakes — scales to systems with billions of parameters.
3.4 Perceptron Learning Algorithm — NOT Gate Worked Example
3.4.1 Hook
Time to run the perceptron learning algorithm by hand. We will teach a single neuron to act as a NOT gate. It flips 0 to 1 and 1 to 0. Step by step, with real numbers.
3.4.2 Purpose
This worked example shows the perceptron learning algorithm on the simplest possible classification problem: the NOT gate (two data points, one feature). You will see weight initialization, forward pass, error checking, weight updates, and convergence — the complete loop.
3.4.3 Inputs and Outputs
Inputs:
- Training data: and
- Initial weights: ,
- Learning rate: (large for illustration; real usage: 0.01–0.1)
- Dummy input (for bias)
Decision rule: if , predict 1; else predict 0.
Outputs: Learned weights that classify both points correctly.
3.4.4 Steps — Full Trace
Initialization:
Epoch 1 — Data Point 1: , target
Since , .
Compare: , . Match. No update.
Weights remain: ,
Epoch 1 — Data Point 2: , target
Since , .
Compare: , . Misclassification! Update weights.
Weight update rule:
For bias (with ):
For :
After Epoch 1: , . Decision line: → .
Epoch 2 — Data Point 1: , target
Since , .
Compare: , . Misclassification! Update:
After update: , . Decision line: → .
Epoch 2 — Data Point 2: , target
Since , .
Compare: , . Match. No update.
Epoch 3 — Data Point 1: , target
Since , .
Compare: , . Match. No update.
Epoch 3 — Data Point 2: , target
Since , .
Compare: , . Match. No update.
Convergence reached! Final weights: , .
Decision boundary: . A vertical line.
- Points with → predicted 1
- Points with → predicted 0
Verification:
- Input 0: → ✓ (target was 1)
- Input 1: → ✓ (target was 0)
Both data points correctly classified.
3.4.5 Visual Intuition
Plot this on a 1D line (the axis). Two points: (target 1, mark as circle) and (target 0, mark as cross). The learned decision boundary is a vertical cut at . The point at falls exactly on the boundary — the algorithm treats as class 1. The point at falls to the right, where , so it is class 0. Any line between and would have worked. The algorithm found , which is one valid answer among many.
3.4.6 Complexity and Cost
This tiny problem converged in 3 epochs with only 3 weight updates. Each epoch visits all 2 data points (4 computations of ). Total cost: trivial. But note that the algorithm "wasted" Epoch 1's first point. The initial zero weights happened to classify it correctly. That was just luck. Real problems take many more epochs.
3.4.7 Pitfalls
- Large learning rate can help or hurt. We used , which made the weights jump dramatically. On a larger dataset, this would cause wild oscillations. Always start small (0.01 or 0.1).
- Thinking zero weights are always fine. Here, gave for every point. That classified everything as 1. This randomly matched the first data point. For asymmetrical datasets, zero initialization may start with all predictions wrong.
- Expecting a unique final answer. The solution works. But so does . The algorithm finds a valid set of weights, not the unique set.
3.4.8 Student Questions and Answers
Q: Does the bias also get adjusted during learning?
A: Yes. The bias uses the same update principle as the other weights. The error gets multiplied by the learning rate and added to the old bias. Since , the bias update is: .
Q: Will this same weight-update formula work for multi-layer neural networks?
A: The simple formula with is only for a single perceptron. The error is directly tied to the output. In a multi-layer network, the error at the output must be distributed backward through all the layers. The update uses the chain rule (backpropagation). The spirit is the same: compute error, find gradient, adjust weights. But the math is much more involved.
3.4.9 Recap and Bridge
The NOT gate example shows the full perceptron learning loop: initialize, forward pass, check error, update weights, repeat. Converged in 3 epochs with final weights , .
Next: how do you know when to stop the algorithm? That is the question of convergence criteria.
3.4.10 Real-World and Domain Connection
The NOT gate example may seem trivial. But it reveals a profound idea. A machine with no prior knowledge — zero weights — can learn a rule purely from examples. This is the foundation of all supervised learning. When a self-driving car learns to detect stop signs, the same loop runs. But now with millions of parameters and millions of examples. The perceptron's three-line update rule was the starting point for all of deep learning.
3.5 Convergence Criteria
3.5.1 Hook
"How do I know when to stop training?" If the algorithm runs too long, you waste time. If it stops too early, the model is not ready. Smart stopping rules save both time and accuracy.
3.5.2 Intuition and Analogy
Think of cooking pasta. You do not keep boiling it forever — you check it. Four tests tell you it is done. The timer went off. It tastes right. It has stopped getting softer. Or you have boiled it long enough and should eat it anyway.
Training a perceptron has four similar stopping conditions. Each works for a different kitchen — or dataset.
Where the analogy breaks: Unlike pasta, which has one correct doneness, a perceptron can have many "good enough" weight configurations. The stopping rule just says "stop adjusting." The final weights may not be perfect — just acceptable.
3.5.3 Formalize — Four Convergence Criteria
The perceptron learning algorithm stops when one of these conditions is met:
- Zero error. Every training point is classified correctly. This is possible only when the data is linearly separable.
- Maximum iterations reached. You set a hard cap — say 1000 epochs. The algorithm stops even if some errors remain. The weights at that point are the final answer.
- No improvement across consecutive iterations. You track the error per epoch. If the error has not decreased for, say, 3 or 4 consecutive epochs, you stop. The algorithm has done all it can.
- Error reduction below a threshold. You measure the drop in error between successive epochs. If the improvement is tiny — below some pre-set value — you stop. Further training is not worth the compute.
3.5.4 Worked Example — Applying Each Criterion
Say you train a perceptron on 500 data points. The error per epoch evolves:
| Epoch | Misclassifications |
|---|---|
| 1 | 120 |
| 2 | 85 |
| 5 | 20 |
| 10 | 0 |
Criterion 1 (zero error): Stops at epoch 10 — perfect.
Criterion 2 (max iterations = 50): Would stop at epoch 50 regardless of error. Here it reaches zero first.
Criterion 3 (no improvement for 3 epochs): If error stayed at 20 for epochs 10–13, it would stop at epoch 13.
Criterion 4 (improvement < 2): If error drops from 22 to 21 (change = 1), below threshold of 2, it stops.
In practice, you often combine criteria: stop at epoch 1000 OR when error < 0.01, whichever comes first.
3.5.5 Learning Rate as a Hyperparameter
The learning rate is a hyperparameter — a setting you choose before training begins. It controls the step size of each weight update.
Typical values: between 0.01 and 0.5. Values above 1 rarely work for real datasets because the adjustments become too large and oscillate.
There is no universal rule for picking . It does not depend on the application domain. The same rules apply to text, images, and prices alike. For each dataset, you experiment. Try . Try . Try . See which converges fastest and use that value.
In later modules, you will see adaptive learning rates — where changes during training, starting large and shrinking over time.
3.5.6 Assumptions and Scope
Scope — Zero error assumes linear separability. Criterion 1 (zero error) only works when a perfect linear decision boundary exists. For real-world data, this is rare. The other three criteria are safety nets.
Scope — Hyperparameters need tuning. The learning rate, maximum iterations, and improvement threshold are all hyperparameters. Setting them is part of the engineering work. There is no formula that picks them for you.
3.5.7 Pitfalls
- Using criterion 1 on non-separable data. If the data is not linearly separable, the algorithm will never reach zero error. It will loop forever without criterion 2 or 3 as a guardrail.
- Setting the learning rate too high. A rate of will cause the weights to jump wildly. The error may oscillate or diverge instead of decreasing. If your cost curve looks like a rollercoaster, lower .
- Confusing hyperparameters with learned parameters. Weights () are learned from data by the algorithm. Hyperparameters (, max iterations) are set by you before training. You tune them, not the algorithm.
- Assuming a larger learning rate always converges faster. A small often converges more reliably. It ends up faster because the algorithm does not waste time overshooting.
3.5.8 Student Questions and Answers
Q: Is the learning rate consistent across different applications?
A: No. The learning rate is not tied to any specific domain. For a given dataset, you experiment: try 0.1, try 0.01, try 0.2. Whichever works best — fastest convergence without oscillation — you use that value.
3.5.9 Recap and Bridge
Training stops when (1) error hits zero, (2) iterations hit the cap, (3) error stops improving, or (4) improvements are too small. The learning rate controls step size and is tuned by experimentation.
Now you have seen the perceptron learn. But what happens when you chain many perceptrons together? That requires data flowing in two directions — forward and backward.
3.5.10 Real-World and Domain Connection
Convergence criteria are used in every modern ML training pipeline. When you train a large language model like GPT, the training log shows a "loss curve." This is a plot of error over training steps. Engineers watch this curve to decide when to stop. Flatlining loss means the model is not learning any more — time to stop. In industry, "early stopping" (a form of criterion 3) is one of the most widely used regularization techniques to prevent overfitting. The principles you learn here on a single perceptron scale directly to billion-parameter models.
3.6 Forward and Backward Propagation
3.6.1 Hook
A single perceptron has just one set of weights to adjust. What happens when you have a thousand perceptrons connected in layers? The data must travel forward to make a prediction — and the error must travel backward to fix every weight. This two-way flow is the heartbeat of deep learning.
3.6.2 Intuition and Analogy
Picture a relay race team passing a baton forward from runner to runner to reach the finish line. At the finish, the coach checks the time and realizes the team was too slow. The coach then walks backward through the lineup, telling each runner how to adjust their handoff.
Forward propagation is the baton going forward — from the starting runner (input) to the finish line (output). Backpropagation is the coach walking back. It distributes feedback to every runner — every weight — so the whole team improves next time.
Where the analogy breaks: In the relay, the coach gives verbal advice. In a neural network, the feedback is mathematical. It is the gradient of the loss with respect to each weight. The chain rule computes this gradient. And the "coach" does not use words — it uses partial derivatives.
3.6.3 Formalize — The Two Passes
Forward propagation (forward pass): Input data enters the network. At each layer, each perceptron computes its weighted sum and applies its activation. The result feeds into the next layer. At the final output layer, you compare the prediction with the target and compute the loss .
Backward propagation (backward pass): The loss is propagated backward through the network. For every weight in every layer, you compute the gradient:
This gradient tells you how much contributed to the error — and in which direction to change it. The chain rule of calculus lets you efficiently compute all gradients in one backward sweep. Each weight is then updated:
The minus sign means: move downhill — in the direction that reduces the error.
3.6.4 The Adjustment Process — Step by Step
- Input → Hidden layers → Output. Pass the data forward using current weights.
- Compute loss. At the output, compare prediction with target using a loss function .
- Compute gradients. Find for every weight in every layer, starting from the output and moving backward.
- Update weights. Every weight gets adjusted: subtract times its gradient.
- Repeat. The full forward-backward cycle repeats for many epochs until convergence.
3.6.5 Trace — A Tiny Two-Layer Network
Consider a network with:
- Input: 2 features
- Hidden layer: 2 perceptrons
- Output: 1 perceptron
Forward pass:
- Hidden layer: ,
- Output:
- Loss:
Backward pass:
- Gradient of loss w.r.t. : how much changing the output affects loss.
- Chain to output weights : how much each contributes.
- Chain further to hidden weights : how the hidden layer's contributions flow through.
Every weight gets a gradient. All weights get updated. The cycle repeats.
This is the core of deep learning. Larger networks just have more links — the principle stays the same.
3.6.6 Visual Intuition
Imagine a multi-story building. Forward propagation: a message goes from the ground floor up each floor to the rooftop. This is the input layer moving through hidden layers to the output. Backward propagation: a correction signal starts at the rooftop and cascades down. It touches every room on every floor. Each room adjusts slightly based on the correction it gets. The building learns the right configuration over many cycles.
3.6.7 Assumptions and Scope
Scope — Intro only. This section gives the intuition. The detailed mathematics of backpropagation — the chain rule applied layer by layer — comes in later lectures. For now, understand the flow: forward for prediction, backward for fixing.
Scope — Works for any differentiable model. Any network where you can compute can use forward-backward training. This covers nearly all modern neural architectures.
3.6.8 Pitfalls
- Thinking backward means time reversal. "Backward" means the direction of the math — gradients flow from output to input. It does not mean the network runs in reverse.
- Forgetting that every link has its own gradient. A network with a million weights computes a million gradients per backward pass. The number of adjustments grows with network size.
- Confusing one update with convergence. A single forward-backward cycle adjusts all weights once. Many cycles (epochs) are needed for the network to converge.
3.6.9 Student Questions and Answers
Q: In a larger network, how are all the weights and biases adjusted?
A: Errors computed at the output are propagated backward, layer by layer. Every weight link between every layer gets a gradient and gets updated. The principle is the same as the single perceptron: compute error, find gradient, adjust weight. But the chain rule connects the gradients across layers, and the number of adjustments grows with the number of weights.
3.6.10 Recap and Bridge
Forward propagation sends data through the network to produce a prediction. Backward propagation sends the error back to update every weight. These two passes repeat until the network learns the pattern.
Next, you will see a practical implementation — using sklearn's built-in perceptron to classify iris flowers.
3.6.11 Real-World and Domain Connection
Forward-backward training is what makes modern AI possible. Every deep learning breakthrough uses the same engine. AlphaGo beating a Go champion. GPT writing coherent text. Midjourney generating art. All rely on forward pass to produce output and backward pass to assign credit to every weight. Google's 2012 "cat detector" used exactly this two-pass mechanism. It had a network with one billion connections. It learned to recognize cats from YouTube videos. The core idea you are learning now scales directly to those systems.
3.6.12 Symbol Registry
| Symbol | Meaning | LaTeX | Type | Domain |
|---|---|---|---|---|
| loss function | scalar | |||
| gradient of loss w.r.t. weight | scalar |
3.7 Using sklearn's Inbuilt Perceptron — Iris Classification
3.7.1 Hook
You have seen the perceptron algorithm by hand. Now let a library do the work. In three lines of Python, sklearn trains a perceptron on real flower data and finds the decision boundary automatically.
3.7.2 Purpose
This section shows how to use the Perceptron class from scikit-learn (sklearn). It is a production-grade implementation of the perceptron learning algorithm. We apply it on the classic Iris flower dataset. The goal: binary classification using an inbuilt model.
3.7.3 Inputs and Outputs
Inputs:
- Iris dataset: 150 samples, 4 features (sepal length, sepal width, petal length, petal width), 3 classes (species 0, 1, 2)
- For binary classification: merge classes 1 and 2 into one group, keeping class 0 separate
- Feature matrix (shape when using two features), target vector
Outputs:
- Trained model with learned
coef_(weights ) andintercept_(bias ) - A linear decision boundary:
3.7.4 Steps — Loading, Training, and Predicting
Step 1 — Load the data:
from sklearn import datasets
iris = datasets.load_iris()
The iris dataset comes built into sklearn. It has 150 examples across 3 species of iris flowers (setosa, versicolor, virginica). Each example has 4 features.
Step 2 — Prepare for binary classification: For simplicity, pick two features (e.g., petal length as , petal width as ). Isolate class 0 (setosa) as one group and combine classes 1 and 2 as the other group. Now you have a binary problem.
# Assume X and y are prepared
# X shape: (150, 2), y values: 0 for setosa, 1 for others
Step 3 — Train the perceptron:
from sklearn.linear_model import Perceptron
model = Perceptron()
model.fit(X, y)
The fit method runs the perceptron learning algorithm internally. It uses a default learning rate, iterates until convergence (or max iterations), and stores the learned parameters.
Step 4 — Inspect the learned weights:
print(model.coef_) # [[w1, w2]] — the feature weights
print(model.intercept_) # [w0] — the bias term
These give the decision line: .
Step 5 — Make a prediction:
prediction = model.predict([[new_x1, new_x2]])
The model classifies the new point based on which side of the decision boundary it falls.
Result: The sklearn perceptron finds a line that cleanly separates setosa from the other two species. Setosa is linearly separable from the rest in the petal-length/petal-width space.
3.7.5 Trace — What Happens Inside fit()
When you call model.fit(X, y), sklearn:
- Initializes weights to zero
- Loops through the data points in each epoch
- For each point: computes the weighted sum, predicts , compares with
- On misclassification: updates weights using the perceptron rule
- Stops when either all points are correctly classified or
max_iteris reached
The Perceptron class can also handle multi-class problems by building multiple binary classifiers internally — one per class pair (one-vs-rest strategy). Each binary classifier has its own set of coefficients.
3.7.6 Visual Intuition
Plot the iris data in a 2D scatter plot with petal length on the X-axis and petal width on the Y-axis. Color the points by species: red for setosa (class 0), blue and green for the other two. The sklearn perceptron draws a straight line through this plane. Setosa points cluster on one side. The other two species cluster on the other side. The line slides between these clusters. This is the same idea as the AND gate and the goa fruit demo. But now with real biological measurements instead of 0s and 1s.
3.7.7 Pitfalls
- Thinking sklearn can solve XOR. The inbuilt
Perceptronuses a single neuron. It cannot handle non-linearly separable data. If you try it on XOR, it will fail — just like the hand-coded version. - Ignoring feature scaling. The perceptron is sensitive to the scale of features. If is in [0, 1] and is in [0, 1000], the weights and the decision boundary can be skewed. Standardizing features (zero mean, unit variance) helps.
- Assuming all data is as clean as iris. The iris dataset is carefully curated. It has no missing values, no errors, and clear class separation. Real-world data is messy. Preprocessing is often the hardest part.
3.7.8 Student Questions and Answers
Q: Are we defining how many perceptrons will be used?
A: The inbuilt Perceptron uses a single perceptron per binary decision. That is why only one linear separation is possible per pair of classes. For complex patterns like XOR, you need at least three perceptrons. Two in the first layer create different regions. One in the second layer combines their outputs. This is the core idea of multi-layer perceptrons.
3.7.9 Recap and Bridge
sklearn's Perceptron class automates the entire perceptron learning algorithm. In three lines — Perceptron(), fit(), predict() — you go from data to a trained binary classifier.
Next, you will code the perceptron yourself from scratch in Python — no library shortcuts — to solidify your understanding.
3.7.10 Real-World and Domain Connection
The Iris dataset is one of the most famous datasets in machine learning history, introduced by Ronald Fisher in 1936. It is the "Hello World" of classification. Every ML practitioner has trained on iris at some point. sklearn itself powers thousands of production systems — from recommendation engines to fraud detection pipelines. The Perceptron class is rarely used in production today. Logistic regression and SVMs are more reliable choices. But it serves as the pedagogical entry point for understanding how all linear classifiers work under the hood.
3.8 Coding Perceptron from Scratch — OR Gate
3.8.1 Hook
Libraries are convenient — but you do not truly understand the perceptron until you code it yourself. Let us build the OR gate perceptron from zero, using only NumPy.
3.8.2 Purpose
This section implements the full perceptron learning algorithm in Python from scratch for the OR gate. You will write the weight initialization, forward pass, weight update, and error tracking loop — all by hand. The goal: understand every line, not just call fit().
3.8.3 Inputs and Outputs
Inputs:
- OR gate data: 4 examples, 2 features, targets in
- Learning rate
- Max iterations: 100
Outputs:
- Learned weights (bias), ,
- Cost history (error per iteration)
- Decision line:
3.8.4 Steps — The Code Walkthrough
Step 1 — Setup and data:
import numpy as np
X = np.array([[0, 0],
[0, 1],
[1, 0],
[1, 1]])
y = np.array([-1, 1, 1, 1])
Using +1/−1 encoding. Both 1/0 and +1/−1 work; this is just the convention chosen here.
Step 2 — Initialize weights to zero:
def initialize_parameters(dim):
W = np.zeros(dim + 1) # +1 for bias
return W
W = initialize_parameters(2) # W = [w0, w1, w2], all zero
Step 3 — Learning loop:
Set . Run for 100 iterations. In each iteration:
- Compute weighted sum: for all 4 points
- Apply threshold: if , ; else
- Compare with target
- Update weights:
- Update bias: (since )
On the factor of : Some code variants use:
The is for mathematical convenience. When the loss is squared error , differentiating brings down a factor of 2 (from the square). The cancels it. Without the , the gradient is , which is twice as large. The algorithm still converges — it just takes steps of a different effective size. The standard perceptron update (without ) is the textbook form. The version with is a code-level shortcut. It changes the effective learning rate. Both are equivalent — only the scale of weight changes differs.
Step 4 — Track cost:
At each iteration, compute a cost value and store it in an array. After 100 iterations, the algorithm produces final weights. Example converged output:
Decision line:
This line correctly separates the OR data points.
Step 5 — Analyze the cost curve:
Plot cost vs. iteration number. The cost drops sharply after 1–2 iterations and stays flat. The algorithm converged well before the 100-iteration cap. This is typical for linearly separable data with a small dataset.
You can use this to implement early stopping: if the cost goes below some threshold, break the loop early and save computation.
3.8.5 Trace — What Each Line Does
Say after epoch 1, point (0,0) is misclassified as +1 when target is −1:
- Error
- update: (no change — was 0)
- update: (no change)
- update:
Now the bias has shifted negative. This makes it harder for (0,0) to produce a positive sum — which is correct, since (0,0) should output −1.
For (0,1), : if it is correctly classified as +1, no update. If wrongly classified, adjusts because was 1 — the weights attached to active inputs get adjusted.
This is the key: the algorithm adjusts weights only for active inputs. If , that weight is not updated. It has no blame for the error.
3.8.6 Complexity and Cost
For 4 data points and 3 parameters, each epoch costs 12 multiply-add operations. The algorithm converges in about 5–10 epochs. Total cost: negligible. For real datasets with thousands of features and millions of points, each epoch is expensive. That is why early stopping (checking when the cost flattens) is practically useful.
3.8.7 Pitfalls
- Confusing the sign of the cost. The cost can be negative here. This code uses with targets of . A negative cost does not mean "negative error" in the absolute sense. It means the predictions tend to overshoot in one direction. What matters is that the cost decreases and stabilizes — not that it reaches exactly zero.
- Assuming the cost must hit zero. The cost may stabilize at a non-zero value. That is fine. The goal is to minimize the error, not erase it. Even a small residual error means the model works well enough.
- Using the factor wrong. Using the variant without including it in the loss means you halve the effective learning rate. The algorithm still converges but slower. Be consistent: the update formula must match the loss function.
3.8.8 Student Questions and Answers
Q: Why is the cost value negative? Shouldn't error always be positive?
A: Error is not always a count. In this code, error is defined as the sum of across data points, with targets of −1 and +1. The difference can be negative. A negative error value is fine — what matters is that the error decreases and stabilizes, not that it reaches exactly zero.
Q: If the error is negative, how do we know if it is good or bad?
A: Good or bad is contextual. Some weights work well for most data points but poorly for a few edge cases. Machine learning aims to find a general pattern — it does not need to be perfect for every single data point. A stable, low-magnitude cost (whether positive or negative) signals a good model.
3.8.9 Recap and Bridge
Coding the perceptron from scratch reveals the algorithm's simplicity: initialize, predict, check error, update weights, repeat. The cost curve shows rapid convergence on simple, linearly separable data.
Next, you will see what happens when the data is NOT linearly separable — the famous XOR problem.
3.8.10 Real-World and Domain Connection
Implementing perceptrons from scratch with NumPy is a standard exercise in ML courses worldwide. In industry, you would use frameworks like PyTorch or TensorFlow. But the underlying mechanics — forward pass, loss computation, gradient-based update — are identical. When you debug a PyTorch model and something goes wrong, knowing what happens under the hood lets you fix it. That is the value of coding it yourself. The code you write here is a miniature version of the training loop inside every deep learning framework.
3.9 The XOR Problem — Non-linearly Separable Data
3.9.1 Hook
AND, OR, NOT — all solved by a single perceptron. Then comes XOR. One neuron cannot solve it. No matter how you twist and turn a single straight line, it cannot separate the red crosses from the blue circles. XOR is the gate that broke the perceptron.
3.9.2 Intuition and Analogy
Imagine a chessboard with only four squares occupied. Two white squares at opposite corners. Two black squares at the other two corners. Your job is to draw one straight line. It must put all white squares on one side and all black squares on the other. No matter how you draw it, one black and one white will always end up on the same side. You cannot do it with one line.
XOR is that chessboard. (0,0) and (1,1) are one class. (0,1) and (1,0) are the other. The classes are diagonal. A single straight line cannot separate diagonals.
The solution? Use two lines — one per perceptron — then combine their results with a third. Two lines can create boxes. A box can isolate diagonal corners.
Where the analogy breaks: Real non-linear problems are not about four points. They are about thousands of points in high-dimensional space. But the principle is the same — one line is not enough.
3.9.3 Formalize — The XOR Truth Table
| Output | ||
|---|---|---|
| 0 | 0 | 0 |
| 0 | 1 | 1 |
| 1 | 0 | 1 |
| 1 | 1 | 0 |
3.9.4 Why a Single Perceptron Fails
Plot the four XOR points on a 2D plane. Color output 0 in red: points (0,0) and (1,1). Color output 1 in blue: points (0,1) and (1,0).
Try drawing any single straight line to put all red on one side and all blue on the other. You cannot. The red points sit at opposite corners of a square. The blue points sit at the other two opposite corners. No line can split diagonal pairs. At best, it separates one red and one blue from the other red and blue.
XOR is not linearly separable. This is the simplest example of nonlinearity. It shows why classification sometimes fails. It captures the fundamental limitation of a single perceptron. One neuron equals one straight line. That is the hard ceiling.
3.9.5 The Solution — Multi-Layer Perceptron (Intuition)
The fix: use more than one perceptron. Arrange them in layers.
- Perceptron 1 draws a line that separates (0,0) from the rest. For example, it learns that points on the "bottom-left" go to one group and everything else goes to another.
- Perceptron 2 draws a different line that separates (1,1) from the rest.
- Perceptron 3 (in the output layer) takes the outputs of Perceptrons 1 and 2 as its inputs. It combines them: if both say "this is a corner," classify as XOR = 0. Otherwise, XOR = 1.
This is a multi-layer perceptron (MLP). Neurons feed into neurons. The output of one layer becomes input to the next. A network of perceptrons can create complex, non-linear decision boundaries. Yet each individual perceptron is still just a straight line.
The standard MLP solution for XOR uses:
- Hidden layer with 2 neurons (using a non-linear activation like ReLU or sigmoid)
- Output layer with 1 neuron
The hidden neurons transform the input space so that the transformed points become linearly separable. The output neuron then draws one line in the transformed space. This is the essence of representation learning — learn a new space where the problem becomes simple.
3.9.6 Trace — What Happens When You Try a Single Perceptron on XOR
If you run the standard perceptron learning algorithm on XOR data:
- The decision line never settles. No matter how the algorithm adjusts weights, one line cannot separate diagonal classes.
- The cost curve oscillates. The error goes up and down across iterations. In some epochs, the line classifies 3 of 4 points correctly (low error). Then it shifts and gets only 2 right (high error). The cost never consistently decreases. The fluctuation is a telltale sign that the data is not linearly separable.
Example cost values across epochs:
| Epoch | Error (misclassifications) |
|---|---|
| 1 | 2 |
| 2 | 2 |
| 3 | 1 |
| 4 | 3 |
| 5 | 2 |
| 6 | 1 |
| 7 | 2 |
| ... | (oscillates forever) |
The algorithm never converges. This is the diagnostic signature of non-linearly separable data.
3.9.7 Visual Intuition
Draw a 2D square with corners at (0,0), (0,1), (1,0), (1,1). Mark (0,0) and (1,1) as red circles (class 0). Mark (0,1) and (1,0) as blue crosses (class 1). Now draw a single straight line. Cut the square any way: vertical, horizontal, diagonal. Always, the line passes through the middle, splitting the square into two halves. Each half contains one red and one blue. This is the geometric proof that XOR is not linearly separable.
Now add a hidden layer. The two hidden neurons transform the square — one neuron pulls (0,0) and (1,1) apart, the other neuron separates (0,1) and (1,0). In the transformed space, the points are arranged in a line, and the output neuron can split them with one cut. The transformation makes a hard problem easy.
3.9.8 Assumptions and Scope
Scope — XOR is the simplest nonlinear problem, not the hardest. Real-world problems have much more complex decision boundaries. But XOR shows the core principle: when linear separability fails, add layers.
Scope — XOR is the simplest nonlinear problem. Real problems have more complex boundaries. But XOR shows the core principle. But neural networks achieve nonlinearity through layers, not through explicit polynomial expansions.
3.9.9 Pitfalls
- Thinking a single perceptron can solve anything. XOR is the counterexample. If someone says "one neuron is enough," show them XOR. This is the simplest proof that single-layer networks are limited.
- Confusing XOR with XNOR. XNOR outputs 1 when both inputs are the same. It is the complement of XOR and is also not linearly separable. Same limitation applies.
- Thinking more epochs will eventually fix XOR. No amount of training helps. A single perceptron on XOR will never converge. The cost will oscillate forever. The only fix is more neurons in more layers.
3.9.10 Student Questions and Answers
Q: In the XOR code, why does the iteration graph only show 20 iterations?
A: The full run went for 100 iterations. The first 20 were zoomed in to show the oscillating cost behaviour in detail. All 100 iterations show the same pattern — the cost keeps fluctuating without consistently decreasing.
Q: Does the error always have to reach zero?
A: No. Zero error is ideal but rare in real-world data. No model achieves 100% accuracy on all problems. You set a threshold — if the error is below that threshold, you accept the model. Perfect zero error is generally not achievable, especially when data has noise or overlapping classes.
Q: How do you decide how many perceptrons are needed?
A: This is determined experimentally. The number of neurons and layers (the network architecture) are design choices you make based on experimentation. Start small, increase until performance stops improving. There is no formula that tells you the right number in advance.
3.9.11 Recap and Bridge
XOR cannot be solved by a single perceptron because the classes are diagonally opposite — no single straight line can separate them. The solution: stack perceptrons in layers. Hidden layers transform the data into a space where a line works.
With the XOR problem, you have seen the need for deeper architectures. Next, a different direction: instead of classification (yes/no), what if the output is a number? That is regression.
3.9.12 Real-World and Domain Connection
The XOR problem was highlighted by Marvin Minsky and Seymour Papert in their 1969 book Perceptrons. They proved mathematically that single-layer perceptrons could not solve XOR and similar problems. This book contributed to the first "AI winter" — a period of reduced funding and interest in neural networks. It took until the 1980s (with the popularization of backpropagation for multi-layer networks) for the field to recover. Today, every deep neural network owes its existence to the XOR insight. The one recognizing your face in a photo. The one translating your speech. All exist because researchers learned: stack neurons, and the impossible becomes possible.
3.10 Introduction to Regression with Single Perceptron
3.10.1 Hook
Classification answers yes/no. But what if the question is "How much?" — what will the temperature be tomorrow? What price should this house sell for? For continuous answers, you need regression.
3.10.2 Intuition and Analogy
Classification is like a bouncer at a club: "In or out?" Binary. Regression is like an appraiser valuing a house. "How much is it worth?" The answer is a number — any number — not a label.
A perceptron for classification uses a threshold to force the output into two bins. For regression, you remove the threshold. The raw weighted sum itself becomes the prediction. No rounding, no binning — just the number.
Where the analogy breaks: An appraiser uses market knowledge and judgment. A regression model uses math to find the line that best fits the data. It minimizes the average squared gap between predictions and true values.
3.10.3 Formalize — Regression vs. Classification
Classification perceptron:
Regression perceptron:
No threshold. No activation function. The weighted sum is the prediction. The output is a continuous value — any real number from to .
The core structure is the same: weighted sum plus bias. The difference is in what you do with the result.
3.10.4 Error Function — Mean Squared Error (MSE)
For classification, you count misclassifications. For regression, you measure how far off the numbers are.
For a single data point, the squared error is:
Expanded (since is the weighted sum):
For all data points, the mean squared error (MSE) is:
Squaring the error punishes large mistakes more than small ones. A prediction off by 10 contributes 100 to the loss. A prediction off by 1 contributes only 1. So MSE is sensitive to outliers. One bad prediction can dominate the total error.
3.10.5 The Objective Function
The machine's goal: find weights that minimize the total loss:
This means: search over all possible weight vectors. . Pick the one that gives the smallest total squared error.
3.10.6 Weight Update Rule for Regression
The update rule uses the gradient of the MSE. For a single data point:
Note the sign: this uses , not . The order is reversed compared to the classification perceptron. Both conventions are equivalent — only the sign of the update flips. The minus sign before means: if (overprediction), decrease the weight. If (underprediction), increase the weight.
Derivation sketch:
The loss for one point is . By the chain rule:
Some textbooks include a in the loss () so that the 2 cancels:
The weight update simplifies. It becomes . Whether you include the or not, the algorithm works — it just changes the effective step size.
3.10.7 Worked Example — Salary Prediction
Problem: Predict salary based on years of experience. You have 3 data points:
| Years () | Salary in thousands () |
|---|---|
| 1 | 50 |
| 3 | 75 |
| 5 | 110 |
Model: (a line). Use .
Start: , . Predictions: for all points.
Errors: , ,
MSE =
After many iterations: Converged weights: , .
Predictions: , ,
Errors: , ,
MSE = — much lower.
Final line: Salary ≈ 32.5 + 14.5 × Years. Sense check: each extra year adds about 14,500 to salary. The intercept (32,500) would be the salary at 0 years experience — a baseline.
3.10.8 Visual Intuition — The Salary Line
Plot years of experience on the X-axis and salary on the Y-axis. The 3 data points form a loose upward trend. The regression line is the perceptron's prediction. It is the best straight line through these points. It minimizes the average squared vertical distance from each point to the line.
The true relationship (in green) is the target pattern. The predicted line (in red) is the model. The gap between the red line and each green dot is the residual (error). The algorithm tweaks and . The intercept sets where the line hits the Y-axis. The slope sets how steep it is. It adjusts both to bring the red line as close as possible to the green points.
3.10.9 Assumptions and Scope
Assumption — Linear relationship. Linear regression assumes the target is roughly a straight-line function of the features. If the true relationship is curved (e.g., salary grows fast early then flattens), a single perceptron will underfit.
Assumption — No outliers. MSE is sensitive to extreme values. One data point with a huge error can pull the line away from the other points.
Scope — Single perceptron regression is a building block. Real regression problems use deep networks with non-linear activations to model complex curves.
3.10.10 Pitfalls
- Forgetting to remove the threshold. A common mistake: coding a perceptron for regression but keeping the threshold function. This turns regression into unintended classification — the output gets binned into categories instead of being continuous.
- Using squared error on data with outliers. Squaring amplifies the effect of outliers. A house priced at 10 million in a dataset of 200K homes will dominate the loss. Consider absolute error or strong loss functions in such cases.
- Confusing regression MSE with classification accuracy. A low MSE does not mean the model is "accurate" in the classification sense. It means the predictions are close to the numbers on average. For regression, you care about the size of the error, not a correct/incorrect count.
3.10.11 Student Questions and Answers
Q: As an engineer, do I only need to provide data, loss function, and threshold?
A: For the simple single perceptron, yes — you provide data, loss function, and hyperparameters. Going forward, you will also design the model architecture: how many layers, how many neurons per layer, which activation functions to use. You select clean quality data and decide how the machine learns. There are many more aspects to control as the course progresses.
3.10.12 Symbol Registry
| Symbol | Meaning | LaTeX | Type | Domain |
|---|---|---|---|---|
| predicted value | scalar | |||
| or | target (actual) value | scalar | ||
| error for one instance | scalar | |||
| MSE | mean squared error | scalar |
3.10.13 Recap and Bridge
Regression uses the same perceptron structure as classification — but removes the threshold. The raw weighted sum is the prediction. The machine minimizes mean squared error (MSE) — the average squared gap between predictions and true values.
This concludes the core concepts. The appendices that follow summarize exam guidance and industry applications for everything covered in this lecture.
3.10.14 Real-World and Domain Connection
Linear regression is possibly the most widely used statistical tool in the world. Economists use it to predict GDP growth. Epidemiologists use it to model disease spread. Real estate platforms (Zillow's Zestimate) use regression — trained on millions of home sales — to estimate property values. Weather services predict tomorrow's temperature using regression on atmospheric measurements. Even advanced deep learning models often end with a regression layer. For example, a self-driving car's steering command is a continuous value. It is predicted by a regression head. The single-perceptron regression you learn here is the foundation of all continuous-value prediction in machine learning.
Exam Guidance Summary
Exam note: The following topics are examinable for Lecture 3. Focus your study on concepts marked with worked examples and step-by-step procedures.
Core Concepts to Master
Perceptron model:
- The mathematical structure: weighted sum followed by a threshold (the linear threshold unit).
- Both output conventions — and — and when each is used.
- The role of bias: or , learned alongside other weights, shifts the decision boundary.
Logic gate design:
- Set up inequalities for AND, OR, and NOT gates from truth tables.
- Solve for valid weights (any solution satisfying all inequalities is correct).
- Understand why these gates are linearly separable.
Perceptron learning algorithm:
- Be able to work through the algorithm step by step for a given dataset. This is similar to the NOT gate worked example in Section 3.4.
- Know the weight update rule: .
- Bias update: same rule with .
Convergence criteria:
- Four stopping conditions: zero error, maximum iterations, no improvement over consecutive iterations, error reduction below threshold.
- Learning rate is a hyperparameter — determined experimentally, not learned from data.
- Typical learning rate values: 0.01 to 0.5.
Forward and backward propagation:
- Forward pass: input → hidden layers → output → loss.
- Backward pass: loss gradient → back through layers → update every weight.
- Understand the flow conceptually; detailed chain-rule derivations come later.
XOR problem:
- Why XOR is not linearly separable (diagonal classes, no single line works).
- Cost curve oscillates — a diagnostic of non-linearly separable data.
- Solution: multi-layer perceptron with hidden layers.
- Two hidden neurons + one output neuron = XOR solved.
Regression with a single perceptron:
- Skip the threshold — the raw weighted sum is the prediction.
- Mean squared error (MSE): .
- Weight update for regression: .
- The factor in some loss functions is for derivative convenience — does not affect correctness.
Study Tips
- Practice the NOT gate trace from Section 3.4 until you can do it from memory.
- Design an OR gate from scratch using inequalities — verify your solution.
- Write the perceptron update loop in Python without looking at notes.
- Draw the XOR 2D plot and explain in one sentence why a single line fails.
Key Industry Applications
Tools and Libraries
scikit-learn (sklearn): The most widely used machine learning library in Python. Its Perceptron class (sklearn.linear_model.Perceptron) implements the perceptron learning algorithm with production-grade optimizations. Use it for quick prototyping and baseline models. Shown on the Iris flower dataset in Section 3.7.
NumPy: The foundational numerical computing library for Python. Provides efficient array operations, linear algebra routines, and random number generation. Every perceptron implementation from scratch uses NumPy's vectorized operations. These compute weighted sums and apply updates in bulk. One operation handles all data points at once.
Benchmark Datasets
Iris Flower Dataset: Introduced by Ronald Fisher in 1936. Contains 150 samples across 3 species (setosa, versicolor, virginica) with 4 features (sepal length, sepal width, petal length, petal width). Available directly via sklearn.datasets.load_iris(). Used as a benchmark for classification algorithms. Setosa is linearly separable from the other two species — making it a perfect test case for a single perceptron.
Real-World Regression Applications
The regression techniques introduced in this lecture power these real-world systems:
- House price prediction: Real estate platforms (Zillow, Redfin) use regression to estimate property values. They use features like square footage, location, number of bedrooms, and year built.
- Weather forecasting: Meteorological agencies use regression to predict weather. They forecast temperature, rainfall, and wind speed from historical patterns and satellite data.
- Stock price prediction: Quantitative finance firms use regression to estimate future prices. They use historical trends, trading volume, and market indicators. (Note: financial prediction is hard; simple linear regression is a starting point, not a complete solution.)
- Crop yield prediction: Agricultural technology companies predict harvest quantities from several inputs. Soil composition, rainfall data, temperature patterns, and fertilizer usage. This helps farmers optimize planting and resource allocation.
- Energy consumption forecasting: Utility companies predict electricity demand from several factors. Time of day, temperature, day of week, and seasonal patterns. This enables efficient grid management and reduces waste.
These applications all share the same structure. Features in. Continuous value out. Model trained by minimizing prediction error. The single-perceptron regression you learn here is the simplest version of these production systems.
DNN Lecture 03 notes · Perceptron Learning and Introduction to Regression
Sections Breakdown
Weighted sum plus threshold; the linear threshold unit and its symbols.
Hand-solving weights for AND, OR, NOT from truth-table inequalities.
Predict, compare, adjust loop that learns weights from data.
Full step-by-step trace of the algorithm on the NOT gate.
Four stopping conditions and the learning rate hyperparameter.
Two-pass flow: forward for prediction, backward for weight updates.
Training and predicting with scikit-learn's Perceptron on iris.
NumPy implementation of the learning loop on the OR gate.
Why one perceptron fails XOR and the multi-layer solution.
Removing the threshold; minimizing mean squared error.
Examinable topics and study tips for the lecture.
sklearn, NumPy, the iris dataset, and real-world regression uses.
Exam Revision Notes
Below is the distilled, exam-ready core of this lecture. Every entry is built from the full textbook notes above. Use this section for rapid review — but if something doesn't make sense, go back to the full explanation in the main content.
Perceptron Mathematical Model
Must-know: A perceptron computes a weighted sum of inputs plus a bias, then applies a threshold (a linear threshold unit). The bias (also ) shifts the decision boundary; the threshold makes the yes/no call.
⚠️ Top pitfall: Confusing the bias with the threshold. The bias is part of the sum; the threshold is the comparison against zero after the sum.
Self-check: For , what does the perceptron predict for input ?
Connects to: Logic gate design, perceptron learning algorithm, regression.
Designing Logic Gates with a Single Perceptron
Must-know: AND, OR, and NOT are linearly separable, so one perceptron can mimic them. Set up one inequality per truth-table row and solve for the weights. Any solution satisfying all inequalities is correct.
⚠️ Top pitfall: Reversing strict () and non-strict () inequalities between output-0 and output-1 rows ruins the gate.
Self-check: Verify that classifies all four AND rows correctly.
Connects to: Perceptron model, XOR problem, multi-layer perceptron.
Perceptron Learning Algorithm
Must-know: The algorithm starts with weights, predicts each point, and on a misclassification nudges every weight by . It repeats until the classes separate. It is guaranteed to converge only if the data is linearly separable.
⚠️ Top pitfall: Assuming convergence means good generalization. A perfect training separator does not guarantee good test performance.
Self-check: On a misclassified point with , which way does move for ?
Connects to: NOT gate worked example, convergence criteria, coding from scratch.
NOT Gate Worked Example
Must-know: The full loop is initialize → forward pass → check error → update weights → repeat. For the NOT gate it converges in 3 epochs with final weights , giving the decision boundary .
⚠️ Top pitfall: Expecting a unique final answer. The algorithm finds a valid weight set, not the unique one (e.g. also works).
Self-check: Trace the NOT gate by hand and confirm both points are classified correctly at convergence.
Connects to: Perceptron learning algorithm, coding from scratch.
Convergence Criteria
Must-know: Training stops when (1) error hits zero, (2) max iterations is reached, (3) error stops improving for consecutive epochs, or (4) the improvement drops below a threshold. The learning rate is a hyperparameter tuned by experiment (typical 0.01–0.5).
⚠️ Top pitfall: Using the zero-error criterion on non-separable data — the algorithm loops forever without a max-iteration guardrail.
Self-check: Why does a learning rate of often fail to converge?
Connects to: Perceptron learning algorithm, XOR problem.
Forward and Backward Propagation
Must-know: Forward pass sends data through the network to a prediction and loss. Backward pass computes the gradient of the loss for every weight and updates it. The minus sign moves the weights downhill to reduce error.
⚠️ Top pitfall: Thinking "backward" means the network runs in reverse. It is the direction of the math — gradients flow output to input via the chain rule.
Self-check: In a two-layer network, which weights get a gradient first during backpropagation?
Connects to: Perceptron learning algorithm, XOR problem, multi-layer perceptron.
sklearn Perceptron and Iris Classification
Must-know: sklearn's Perceptron automates the whole algorithm: Perceptron(), fit(X, y), predict(). Learned weights live in coef_ and the bias in intercept_. It draws one linear boundary per binary decision.
⚠️ Top pitfall: Believing sklearn can solve XOR. A single inbuilt perceptron still cannot handle non-linearly separable data.
Self-check: Why must you standardize features before training a perceptron?
Connects to: Logic gates, XOR problem, coding from scratch.
Coding a Perceptron from Scratch (OR Gate)
Must-know: From-scratch code reveals the loop: initialize weights to zero, compute the weighted sum, apply the threshold, compare with the target, and update. With the OR gate converges to roughly .
⚠️ Top pitfall: Mixing up the factor. If you put in the loss, the update halves — keep the formula consistent with the loss.
Self-check: Why does a point with never change during an update?
Connects to: Perceptron learning algorithm, NOT gate, sklearn perceptron.
The XOR Problem
Must-know: XOR is not linearly separable — the two classes sit on opposite diagonal corners, so no single straight line splits them. A single perceptron's cost curve oscillates forever. The fix is a multi-layer perceptron: 2 hidden neurons + 1 output neuron.
⚠️ Top pitfall: Thinking more epochs will eventually fix XOR. It will not — only adding layers (more neurons) solves it.
Self-check: Draw the 2D XOR plot and state in one sentence why one line fails.
Connects to: Logic gates, forward/backward propagation, multi-layer perceptron.
Regression with a Single Perceptron
Must-know: For regression, remove the threshold — the raw weighted sum is the prediction. The model minimizes mean squared error (MSE). The update uses , the reverse order from classification.
⚠️ Top pitfall: Forgetting to drop the threshold turns regression into unintended classification — the output gets binned instead of staying continuous.
Self-check: For the salary data, what does the converged line predict for 4 years of experience?
Connects to: Perceptron model, perceptron learning algorithm, mean squared error.
Was this lecture useful?
BitsNotes AI Assistant
Subject Notes AssistantConfigure AI Chat
Choose how to access the chatbotSigned in as
Powered by BitsNotes — 20 messages per day. No API key needed. Want unlimited access? Use "Bring Your Own Key" mode.
Sign in to use AI Chat
Get 20 free AI messages per day to ask questions about your lecture notes. Sign in with Google or GitHub — it takes 5 seconds.
Sign In to BitsNotesSwitch to "Bring Your Own Key" tab above for unlimited access with any OpenAI-compatible provider.