AI from scratch · Chapter 3

A neuron from scratch

An artificial neuron is almost embarrassingly simple: multiply each input by a weight, add them up with a bias, and push the total through a bend. That's it. Yet put enough of them together and they recognize faces and write code. Let's build one, look at what it sees, and watch it learn.

1. A weighted sum and a bend

Our neuron looks at a point with two numbers, (x₁, x₂). It computes

z = w₁·x₁ + w₂·x₂ + b   →   output = σ(z) = 1 / (1 + e−z)

The bend σ (the sigmoid) squashes any number into 0…1, so the output reads like "how sure am I that this point is blue?". The two weights form an arrow, w. Drag its tip, slide the bias, and drag the green probe point.

Look at the shading: the neuron splits the plane with a straight line, where z = 0 and it's exactly 50% sure. That line is always perpendicular to the weight arrow. The arrow points toward "more blue", its length says how sharp the switch is (a long arrow means a crisp edge, a short one a fuzzy blur), and the bias slides the line back and forth without turning it. Remember chapter 1: w₁·x₁ + w₂·x₂ is a matrix with one row. A neuron is a tiny layer.

The math, step by step

Written with chapter 1's dot product, the neuron is

\[ z = w \cdot x + b, \qquad \hat p = \sigma(z) = \frac{1}{1 + e^{-z}} \]

Why the edge is a straight line perpendicular to \(w\): the edge is where \(z = 0\), i.e. \(w \cdot x = -b\). Take two points \(p\) and \(q\) on it. Then \(w \cdot p = w \cdot q = -b\), so \(w \cdot (p - q) = 0\): the edge's direction \(p - q\) is at right angles to \(w\). The edge sits at distance \(|b| / \lVert w \rVert\) from the origin.

Why a long arrow makes a crisp edge: walk a distance \(d\) away from the edge along \(w\)'s direction and \(z\) grows by \(\lVert w \rVert\, d\). Double \(w\) and the sigmoid's S-curve is squeezed into half the width.

And why the sigmoid: it turns "how far past the edge" into a probability. \(\sigma(0) = 0.5\), \(\sigma(2) \approx 0.88\), \(\sigma(-2) \approx 0.12\), \(\sigma(5) \approx 0.993\). It also has a slope that's easy to compute from its own output: \(\sigma'(z) = \sigma(z)\,(1 - \sigma(z))\). We'll need that in a minute.

A neuron draws one straight line across its inputs and reports how far past the line a point is, squashed into a probability.

Weights \(w = (2, -1)\), bias \(b = 1\), point \(x = (1, 1)\). What is \(z\)?

\(z = 2 \cdot 1 + (-1) \cdot 1 + 1 = 2\).

…and the neuron's output \(\sigma(z) = 1/(1 + e^{-2})\)? (Two decimals; \(e^{-2} \approx 0.135\).)

\(1 / 1.135 \approx 0.88\): 88% sure the point is blue.

2. Watch it learn

Here are two clouds of points. We want the neuron to say "blue" for blue points and "red" for red ones. Its loss (how wrong it is) is the log loss: for each point, how surprised the neuron is by the right answer. Training is chapter 2's loop: compute the gradient of the loss with respect to w₁, w₂, b, step downhill, repeat.

Drag points around · click empty space to add a blue point, shift-click (or long-press) for red

Notice what the gradient does here, in plain words: every misclassified point pulls the line toward itself and pushes the weight arrow toward its own side. Points the neuron already gets right, with confidence, barely pull at all. That's the whole of learning for one neuron: lots of small nudges from its mistakes.

The math, step by step

Label blue points \(y = 1\) and red ones \(y = 0\). The log loss of one point is the surprise at the truth:

\[ L = -\big[\, y \ln \hat p + (1 - y) \ln (1 - \hat p) \,\big] \]

For a blue point that's \(-\ln \hat p\); for a red one, \(-\ln(1 - \hat p)\). To train we need \(\partial L / \partial w\). Go in two hops (the chain rule):

\[ \frac{\partial L}{\partial \hat p} = -\frac{y}{\hat p} + \frac{1 - y}{1 - \hat p}, \qquad \frac{\partial \hat p}{\partial z} = \hat p (1 - \hat p) \]

Multiply them and almost everything cancels:

\[ \frac{\partial L}{\partial z} = \hat p - y, \qquad \frac{\partial L}{\partial w} = (\hat p - y)\, x, \qquad \frac{\partial L}{\partial b} = \hat p - y \]

That's the pull you see in the picture, as a formula. \(\hat p - y\) is "how wrong", between −1 and 1. A blue point the neuron calls 20% blue has \(\hat p - y = -0.8\): a strong pull, and the step \(w \leftarrow w - \eta (\hat p - y) x\) moves \(w\) toward \(x\). A blue point at 99% has −0.01: barely any pull. Averaged over all points, that's one training step.

Learning is many small nudges: each point pulls by how wrong it is, \(\hat p - y\), so mistakes teach and confident right answers barely matter.

Why log loss, and not squared error, for a probability?
  1. Try squared error instead, \(L = (\hat p - y)^2\). Chain rule: \(\partial L / \partial z = 2(\hat p - y) \cdot \hat p (1 - \hat p)\).
  2. Take a blue point the neuron is confidently wrong about: \(\hat p = 0.001\). The first factor is about −2, a big error, but \(\hat p(1 - \hat p) \approx 0.001\), the sigmoid's flat tail.
  3. So the pull is about 0.002: the neuron barely moves exactly when it's most wrong. Squared error and a sigmoid fight each other.
  4. With log loss, the \(1/\hat p\) in its slope cancels the sigmoid's \(\hat p(1 - \hat p)\), leaving \(\hat p - y \approx -1\): the strongest pull possible. Log loss is also a bowl in \(w\) (calculus 5), so there's one best line, and it's what maximum likelihood gives (probability 3).
Where it breaks: data that's too easy, and labels that are wrong

A blue point (\(y = 1\)) at \(x = (2, 1)\); the neuron says \(\hat p = 0.2\). What is \(\partial L / \partial z\)?

\(\hat p - y = 0.2 - 1 = -0.8\). Then \(\partial L/\partial w = -0.8 \cdot (2, 1) = (-1.6, -0.8)\), and stepping against it adds a multiple of (2, 1) to \(w\): the weight arrow turns toward the point.

A red point (\(y = 0\)) that the neuron is 99% sure is red (\(\hat p = 0.01\)). How much does it pull on the weights?

Points that are already right and confident contribute almost nothing to the gradient. Learning is driven by the mistakes and the near-misses.

3. What one neuron can't do

Now a pattern a child can see: blue in two opposite corners, red in the other two (it's called XOR). Train the single neuron on it.

It can't. However it turns its line, one straight cut can't put opposite corners together, so it gets stuck around half right. This exact problem stalled neural network research for a decade in the 1970s. The fix is the one from chapter 1: stack layers. Four neurons in a hidden layer each make their own cut; a final neuron combines their answers, and now the boundary can bend around the corners. Press the second button and watch it curve.

The math, step by step

Why no line works: suppose \(w_1 x_1 + w_2 x_2 + b\) is positive at (0, 1) and (1, 0) (blue) and negative at (0, 0) and (1, 1) (red). Add the two blue inequalities: \(w_1 + w_2 + 2b > 0\). Add the two red ones: \(w_1 + w_2 + 2b < 0\). Both can't be true. No weights exist.

With a hidden layer it's easy, even by hand. XOR is "OR, but not AND", so build those as neurons with big weights (a big weight makes the sigmoid act like a switch):

\[ h_1 = \sigma(20x_1 + 20x_2 - 10)\ \ (\text{OR}), \quad h_2 = \sigma(-20x_1 - 20x_2 + 30)\ \ (\text{NAND}), \quad \hat p = \sigma(20h_1 + 20h_2 - 30)\ \ (\text{AND}) \]

The hidden layer moves the four corners to new positions \((h_1, h_2)\) where one straight line does separate them: (0,0) → (0, 1), (1,1) → (1, 0), and both blue corners → (1, 1). That's chapter 1's picture again: move and fold space until the answer is a straight cut.

One neuron can only cut with a straight line. A hidden layer moves the points to new positions where a straight cut works.

In the hand-built network, where does the corner (1, 1) end up in the hidden layer, \((h_1, h_2)\)?

\(h_1 = \sigma(30) \approx 1\), \(h_2 = \sigma(-10) \approx 0\). The output neuron (AND) then gets \(20 + 0 - 30 = -10\): red, correctly.

But how did that hidden layer learn? Each of its neurons had to figure out its share of the blame for the final answer, through the neuron after it. Passing blame backwards like that is backpropagation: the next chapter.

All chapters: AI from scratch. Inspired by 3Blue1Brown's Neural Networks series.

Last updated