TactivergeLite

Lite / Textbooks / Introduction to Intelligent Systems / Chapter 7

7. Learning from data

Version 1 · Technically checked (automated checks only) · 4 source lessons · Full interactive version

Introduction

Sometimes the rule is easier to learn than to write. A perceptron weighs its inputs, adds a bias and draws one straight line between two classes. Gradient descent adjusts the weights a little at a time to shrink the error. This chapter trains a single neuron by hand, shows why one line cannot solve every problem, checks a model fairly with cross-validation, and asks whether the result fits in a small device's memory, time and energy.

Figure 7.1. One neuron, one line (described in words)

A perceptron with weights 1 and 1 and bias −1.5 draws the line x1 + x2 = 1.5 across the unit square. The points (0, 0), (0, 1) and (1, 0) give z below zero and output 0; only (1, 1), with z = 0.5, gives 1, so the neuron computes AND.

Explanation

Built from 4 School lessons. Each part is the lesson's own explanation.

7.1 The perceptron: one neuron draws one line

The first learning machine, built in 1958, could tell shapes apart by nudging a few numbers. What exactly was it nudging, and what could it never learn?

Weighted sum, bias, step

A perceptron takes inputs x₁, x₂, … and computes z = w₁x₁ + w₂x₂ + … + b. The weights say how much each input matters (and in which direction); the bias b shifts the result. A step function then decides: output 1 if z ≥ 0, else 0. With w = (2, 1) and b = −6, the input (3, 1) gives z = 6 + 1 − 6 = 1, so output 1; the input (1, 2) gives z = −2, so output 0.

The decision boundary is a line

The output switches where z = 0: for two inputs, w₁x₁ + w₂x₂ + b = 0 is a straight line. With w = (2, 1), b = −6 it is 2x₁ + x₂ = 6, through (3, 0) and (0, 6). The weight vector points across the line towards the class-1 side; scaling all weights and bias together changes nothing about the line. Changing b slides the line without turning it.

Learning by fixing mistakes

The perceptron rule looks at one example at a time. If it is right, nothing changes. If it is wrong, each weight moves by η(t − y)xᵢ and the bias by η(t − y), where t is the target, y the output and η the learning rate. A missed 1 (t − y = +1) adds the input to the weights, raising z for that input next time; a false 1 subtracts it. If a separating line exists, this is guaranteed to find one.

The XOR wall

XOR labels (0, 0) and (1, 1) as one class and (0, 1) and (1, 0) as the other. No straight line separates them, so a single perceptron keeps getting at least one point wrong forever. Adding a hidden layer of neurons fixes this: two lines combined can carve out the diagonal pair. That insight, and a way to train hidden layers, is what turned perceptrons into neural networks.

Common mix-ups

Open the Lite lesson: The perceptron: one neuron draws one line

7.2 Gradient descent on a one-neuron network

A network with millions of weights learns by asking one question of each weight: “if I nudge you, does the error go up or down?” How is that question answered?

A smooth neuron and its loss

Replace the hard step with the sigmoid σ(z) = 1/(1 + e^(−z)), which glides from 0 to 1. One neuron computes y = σ(wx + b). To measure how wrong it is on an example with target t, use the squared-error loss L = ½(y − t)². The ½ is only there to cancel a 2 when we differentiate. Training means choosing w and b to make L small across the data.

Blame by the chain rule

L depends on w only through z and y, so ∂L/∂w = (∂L/∂y)(∂y/∂z)(∂z/∂w) = (y − t) · y(1 − y) · x. Each factor has a meaning: how wrong the output is, how sensitive the sigmoid is at this point (at most 0.25, at z = 0), and how big the input was. A zero input gets no blame. The same idea, repeated backwards through layers, is backpropagation.

One step downhill

Gradient descent updates w ← w − η·∂L/∂w: move against the gradient, scaled by the learning rate η. Take w = 0.5, b = 0, x = 2, t = 1. Then z = 1, y ≈ 0.7311, ∂L/∂w ≈ (−0.2689)(0.1966)(2) ≈ −0.1058. With η = 1, w becomes ≈ 0.6058 and the loss falls from ≈ 0.0362 to ≈ 0.0263. Negative gradient, so w went up.

Choosing the learning rate

For the bowl L(w) = (w − 3)², each step multiplies the distance from the minimum by (1 − 2η). With η = 0.1 the distance shrinks by 0.8 per step: safe but slow. η = 0.5 lands exactly on the minimum. Between 0.5 and 1 it overshoots but still settles; above 1 the distance grows every step and training diverges. Real loss surfaces are not perfect bowls, which is why η is tuned and often decreased over time.

Derivation: ∂L/∂w for one sigmoid neuron
  1. Define z = wx + b, y = σ(z) = 1/(1 + e^(−z)), and L = ½(y − t)².

  2. Outer link: ∂L/∂y = (y − t), because the ½ cancels the 2 from differentiating a square.

  3. Middle link: dσ/dz = e^(−z)/(1 + e^(−z))² = σ(z)·(1 − σ(z)) = y(1 − y).

  4. Inner link: ∂z/∂w = x (and ∂z/∂b = 1).

  5. Multiply the links (chain rule): ∂L/∂w = (y − t) · y(1 − y) · x, and ∂L/∂b = (y − t) · y(1 − y).

  6. Update: w ← w − η(y − t)y(1 − y)x. Check with numbers: w = 0.5, b = 0, x = 2, t = 1 gives ∂L/∂w ≈ −0.1058; η = 1 gives w ≈ 0.6058, and the loss drops from ≈ 0.0362 to ≈ 0.0263.

Common mix-ups

Open the Lite lesson: Gradient descent on a one-neuron network

7.3 Cross-validation: grading a model fairly

Your classifier scores 97% on your data, then 71% on the device in the field. Which number was lying, and how could you have known before shipping?

Why one split is not enough

Testing on the data you trained on rewards memorising: an overfitted model scores brilliantly and fails in the field. A single held-out split is honest but noisy, especially with little data: which examples happened to land in the test set can swing the score by several per cent. k-fold cross-validation reduces that luck by repeating the split k times.

The k-fold recipe

Shuffle (unless order matters), then cut the data into k equal folds. For each fold in turn: train a fresh model on the other k − 1 folds, test it on this one, record the score. With 1000 examples and k = 5, each model trains on 800 and is tested on 200. Report the mean of the k scores and their spread (standard deviation or range). Common choices are k = 5 or 10.

Reading the spread

Fold scores of 82, 85, 79, 88 and 81% have mean 83.0% and sample standard deviation about 3.5 points. That spread is part of the result: a rival model scoring 84% is not clearly better. A large spread means the model is sensitive to which data it sees, often a sign of too little data or of a few unusual examples clustered in one fold.

Leakage and the final test

Leakage is test information sneaking into training: normalising with statistics computed on all the data before splitting, near-duplicate recordings in different folds, or shuffling time-series so the model trains on the future. Do every preprocessing step inside each fold, and split by recording session or device, not by row. Use cross-validation to choose models; keep a separate test set you touch once, at the very end.

Common mix-ups

Open the Lite lesson: Cross-validation: grading a model fairly

7.4 Fitting a model into memory, time and energy

A smartwatch must recognise a gesture in 20 ms, using under 1 mJ, with 64 KB of RAM. Can your model do it? Work it out before you build it.

The budget table

Write one row per resource: flash (weights + code), RAM (peak activations + buffers + stack), latency (MACs ÷ MAC rate + overheads) and energy (MAC energy + memory energy + idle energy). Each has a limit from the product requirement. The design is feasible only if every row fits, with a margin.

Energy per inference

E ≈ MACs × e_MAC + bytes moved × e_byte + P_idle × time. Because e_byte can be tens to hundreds of times e_MAC (depending on which memory), a model with fewer weight reads can beat one with fewer MACs. Reusing data already in registers or SRAM is the key trick of efficient accelerators.

Which knob?

Too big for flash: quantise or prune. Too big for RAM: process in smaller tiles, or choose layers with smaller activations. Too slow: fewer MACs, SIMD instructions or an accelerator. Too much energy: reduce data movement, then MACs, then duty-cycle the device. Each change must be re-checked against accuracy on held-out data.

Common mix-ups

Open the Lite lesson: Fitting a model into memory, time and energy

Worked examples

The perceptron: one neuron draws one line: example 1

w = (1, −2), b = 3. Classify the input (4, 1).

Solution

z = 1×4 + (−2)×1 + 3 = 4 − 2 + 3 = 5 ≥ 0, so the output is 1.

The perceptron: one neuron draws one line: example 2

The perceptron above wrongly outputs 1 for (4, 1), whose target is 0. Apply one update with η = 0.5.

Solution

t − y = 0 − 1 = −1. w₁ = 1 + 0.5×(−1)×4 = −1; w₂ = −2 + 0.5×(−1)×1 = −2.5; b = 3 + 0.5×(−1) = 2.5. Now z = −4 − 2.5 + 2.5 = −4: output 0, correct.

Gradient descent on a one-neuron network: example 1

For L(w) = (w − 3)², start at w = 5 with η = 0.25. Take one step.

Solution

dL/dw = 2(5 − 3) = 4. New w = 5 − 0.25 × 4 = 4. The distance to the minimum halved, from 2 to 1, because 1 − 2η = 0.5.

Gradient descent on a one-neuron network: example 2

A sigmoid neuron has z = 0. What is σ'(z), and why does it matter?

Solution

σ(0) = 0.5, so σ'(0) = 0.5 × 0.5 = 0.25: the largest slope the sigmoid ever has. Far from z = 0 the slope tends to 0, so a saturated neuron barely learns (the vanishing-gradient problem).

Cross-validation: grading a model fairly: example 1

A dataset has 500 examples and you use 10-fold cross-validation. How many examples does each model train on and test on?

Solution

Each fold has 500 / 10 = 50 examples. Each model tests on 50 and trains on the other 450.

Cross-validation: grading a model fairly: example 2

Fold accuracies are 82, 85, 79, 88 and 81%. Report the result properly.

Solution

Mean = 415 / 5 = 83.0%. Sample standard deviation = √(50 / 4) ≈ 3.5 points. Report 83.0% ± 3.5 (5-fold CV), range 79–88%.

Fitting a model into memory, time and energy: example 1

Budget check: 32,128 MACs and 32 KB of int8 weights; 1 MAC/cycle at 48 MHz; 3 pJ/MAC; 25 pJ/byte from flash. Latency and energy?

Solution

Latency = 32,128/48×10⁶ ≈ 0.67 ms. Energy = 32,128×3 pJ + 32,768×25 pJ ≈ 0.096 µJ + 0.82 µJ ≈ 0.92 µJ: memory dominates by about 8×.

Interactive figures, in words

Figure 7.2 from The perceptron: one neuron draws one line

Use the separable dataset with η = 0.5 and press “Show next example” repeatedly. Watch the line jump only when a point is misclassified. Then switch to the XOR pattern and run several full passes: does it ever settle?

The perceptron diagram plots six points on a 0–5 grid: class 0 (circles) at (1, 1), (2, 1) and (1, 3); class 1 (squares) at (3, 4), (4, 2) and (4, 4). Weights start at zero. Each step shows one example; if it is misclassified the weights and bias change by η(t − y)x and the decision line moves. The readout gives the weights, the bias and how many points are misclassified; on this set it reaches zero. On the XOR set ((1, 1) and (4, 4) class 0; (1, 4) and (4, 1) class 1) at least one point is always wrong.

Figure 7.3 from Gradient descent on a one-neuron network

Start at w₀ = −1. Take steps with η = 0.1, then 0.5, then 0.9, then 1.05. For each, count steps until the readout says converged, or note when it never does.

The gradient-descent diagram plots the loss L(w) = (w − 3)² + 1 as a U-shaped curve with its lowest point at w = 3. Each press of Take one step moves w by −η × 2(w − 3) and marks the new point. From w₀ = −1: with η = 0.1 the points creep towards 3; with η = 0.5 the first step lands exactly on 3; with η = 0.9 they zig-zag across the minimum but settle; with η = 1.05 each zig-zag is wider and the readout warns that training is diverging.

Figure 7.4 from Cross-validation: grading a model fairly

Choose k = 2, then 4, then 6. Click through the held-out folds. How do the fold accuracies, their mean and their spread change as k grows?

The k-fold diagram shows 24 labelled readings as a row of boxes numbered by fold (example i belongs to fold i mod k); the held-out fold is filled in. For each fold a threshold classifier is trained on the other folds (threshold halfway between the two class means) and tested on the held-out fold. A list gives each fold's training size, test size and accuracy, and the readout reports the mean accuracy, its standard deviation and its range for k = 2, 3, 4 or 6.

The interactive versions are in the full chapter.

Laboratory

These run in a browser on the full site (they need a faster connection). Simulations are simplified educational models.

Practice

Each question links to its Lite lesson, where your answer is checked on our server and a wrong answer gets a hint. Answers are never sent to your device.

  1. A perceptron has w₁ = 1, w₂ = −2 and b = 3. What is z for the input (x₁, x₂) = (4, 1)?
    Answer it in “The perceptron: one neuron draws one line”
  2. You increase a perceptron's bias b and leave the weights alone. What happens to its decision line?
    Answer it in “The perceptron: one neuron draws one line”
  3. Why can a single perceptron never classify all four XOR points correctly?
    Answer it in “The perceptron: one neuron draws one line”
  4. For L(w) = (w − 3)², start at w = 5 with learning rate η = 0.25. What is w after one gradient-descent step?
    Answer it in “Gradient descent on a one-neuron network”
  5. During training the loss jumps around and then grows larger every epoch. What is the most likely cause?
    Answer it in “Gradient descent on a one-neuron network”
  6. Which of these causes data leakage in cross-validation?
    Answer it in “Cross-validation: grading a model fairly”
  7. Fold accuracies are 90, 72, 88, 91 and 74%. What should you report?
    Answer it in “Cross-validation: grading a model fairly”
  8. Your model's weights fit in flash, but one layer's input and output activations together exceed RAM. What is the most direct fix?
    Answer it in “Fitting a model into memory, time and energy”

Engineering applications

Keyword spotting

A smart speaker's wake-word detector is a small network running all the time on a low-power chip. It must fit in a few hundred kilobytes and draw only milliwatts.

Gesture recognition

A wristband can learn the motion pattern of a tap or a wave from labelled examples. Cross-validation across different people shows whether it will work for someone new.

Watch (optional)

Streaming video uses a lot of data. Everything you need is in the text.

Summary

Glossary

Truth table
A truth table lists the output of a logic function for every possible combination of its inputs; n inputs need 2^n rows. Field Guide
AND gate
An AND gate outputs 1 only when all of its inputs are 1. Field Guide
XOR gate
An XOR gate outputs 1 when its inputs are different and 0 when they are the same. Field Guide

Project: Train a neuron, then grade it fairly

Create or choose a small two-feature data set (for example, ripe or unripe fruit from colour and firmness readings you simulate). Train a perceptron, evaluate it with 5-fold cross-validation, and report the mean accuracy, its spread and one failure case.

Deliverables

Write it up on paper or in your own notes. Lite never stores what you write.

References

← 6. State estimation and sensor fusion8. Evaluating intelligent systems honestly →