Skip to content

2.3 Perceptron and logistic regression

ready≈ 8.5 hoursNeeds: 2.2Unlocks: 2.4, 3.1
  1. 1 Learn
  2. 2 Bridge & derive
  3. 3 Explore (Perceptron playground, Logistic boundary)
  4. 4 Do
  5. 5 Check

A linear classifier scores an input with z=w⊤xz = \mathbf{w}^\top\mathbf{x} (bias included as w0w_0) and splits the plane along the line z=0z = 0. The vector (w1,w2)(w_1, w_2) is perpendicular to that line and points toward the positive side (MML §12.1, on separating hyperplanes).

The perceptron uses labels ±1\pm1 and one rule: visit the points in turn and, when one is on the wrong side (y w⊤x≤0y\,\mathbf{w}^\top\mathbf{x} \le 0), add yxy\mathbf{x} to w\mathbf{w}. That nudges the score of that point toward the correct sign. Fold the bias in by appending a constant 1 to every x\mathbf{x}. If some unit vector w∗\mathbf{w}^* gives every point y w∗⊤x≥γy\,\mathbf{w}^{*\top}\mathbf{x} \ge \gamma, and every ∥x∥≤R\lVert\mathbf{x}\rVert \le R (both measured with that extra 1 included), the perceptron makes at most (R/γ)2(R/\gamma)^2 mistakes in total, whatever order it visits the points in (Novikoff’s bound, proof in Collins’ notes). The margin is not the gap you see in the input plane: far from the origin, a wide-looking gap can mean a tiny γ\gamma. CS229 §2.2 shows the same algorithm with labels 0 and 1. If the data are not separable, it never settles.

Logistic regression turns the score into a probability, p=σ(z)=1/(1+e−z)p = \sigma(z) = 1/(1+e^{-z}), with labels in {0,1}\{0, 1\}, and maximises the likelihood of the labels. Taking the negative log gives the log-loss (binary cross-entropy from module 1.5), −[ylog⁡p+(1−y)log⁡(1−p)]-[y\log p + (1-y)\log(1-p)] (CS229 notes §2.1). Its gradient has the same form as linear regression’s, 1nX⊤(p−y)\frac1n\mathbf{X}^\top(\mathbf{p}-\mathbf{y}): prediction minus target, routed back through the inputs. The derivation below shows why. The loss is convex, so gradient descent finds the best line, and unlike the perceptron it gives a sensible answer when the classes overlap.

Two numerical traps. np.exp(-z) overflows for very negative zz, and log⁡(σ(z))\log(\sigma(z)) becomes log⁡0\log 0 once σ\sigma rounds to 0 or 1. Compute log⁡σ(z)=−log⁡(1+e−z)\log\sigma(z) = -\log(1+e^{-z}) with np.logaddexp, and never call exp on a large positive number (NumPy, logaddexp).

XOR. Label the corners of a square by whether x1x2>0x_1x_2 > 0. No line puts both positive corners on one side and both negative corners on the other, so every linear classifier gets at least one of the four wrong. This was the famous objection to perceptrons (Minsky and Papert, via Wikipedia). Adding the feature x1x2x_1x_2 makes the data separable. Part 3’s neural networks learn such features instead of being handed them.

Gradient of the logistic loss is Xᵀ(σ(Xw) − y)step 1 of 5
  1. σ(z)=11+e−z  ⇒  σ′(z)=e−z(1+e−z)2=σ(z) (1−σ(z))\sigma(z) = \frac{1}{1+e^{-z}} \;\Rightarrow\; \sigma'(z) = \frac{e^{-z}}{(1+e^{-z})^2} = \sigma(z)\,(1-\sigma(z))

★ Perceptron playground

How the boundary moves; why XOR fails

Static view on small screens. Open this page on a laptop to interact.

click adds:
w = [b, w₁, w₂] = [0.00, 0.00, 0.00] epoch 1, next point #1 accuracy 50% mistakes per epoch: —

The dashed ring marks the next point to visit. Step through one point at a time and watch w (the arrow, which is perpendicular to the boundary) move only on mistakes. On XOR the mistakes never reach zero: no line separates it.

A 2-D perceptron. Circles are class +1, squares class −1, and misclassified points have a red outline. The line is the decision boundary, the arrow is the weight vector (w₁, w₂), and a dashed ring marks the next point the algorithm will visit. Step one point at a time, a whole epoch, or run to convergence. The text below explains each update. Click the plot to add points of the chosen class. Keyboard: Tab to the buttons: Step, Epoch, Run, Reset; points are added by clicking on the plot.

Logistic boundary

Probabilistic classification and log-loss

Static view on small screens. Open this page on a laptop to interact.

mean log-loss 0.9647 ‖∇L‖ 0.5454 accuracy 60% slope of p at the boundary ∝ ‖(w₁, w₂)‖ = 1.41

Shading is p(y = +1 | x) = σ(b + w₁x₁ + w₂x₂); the solid line is p = 0.5 and the thin lines p = 0.1 and 0.9. Each point is drawn bigger the more log-loss it costs. Scale all three weights up together: the boundary stays put but the band between 0.1 and 0.9 narrows. On separable data the loss keeps shrinking as the weights grow forever, which is one reason to regularize.

Logistic regression in 2-D. Sliders set the bias and the two weights, and the shading shows the predicted probability of class +1. The solid line is p = 0.5 and the dashed lines are p = 0.1 and 0.9. Each point’s size grows with its log-loss. A button runs 400 steps of gradient descent from the current weights. Keyboard: Tab through the sliders; arrow keys adjust them.

Implement the perceptron, a sigmoid that never overflows, the log-loss and its gradient, and gradient descent. Then run the XOR experiment: both linear models fail, and one extra feature fixes them.

Perceptron, logistic regression and XOR stubs/m2_3_classifiers.py

Loading starter file…

Prefer your own editor? Edit exercises/stubs/m2_3_classifiers.py and run mlc check 2.3. The tests are identical; import the results on the progress page.

Hints · sigmoid 0/3 revealed
Hints · logistic_loss_and_grad 0/3 revealed
Hints · perceptron_fit 0/3 revealed

Locally: mlc check 2.3.

1. What does the perceptron convergence theorem guarantee?
2. Logistic weights (b, w₁, w₂) = (0, 2, 0). What is p(y = 1) at x = (1, 5)?
3. You multiply all logistic weights by 10. The p = 0.5 boundary…
4. Why does no linear classifier get XOR fully right?
5. Your loss is nan after a few steps of training. The most likely cause is…
  • not yet: All tests pass (0/?)
  • not yet: Checkpoint quiz ≥ 80%
Finish the items above first.
Learner log: time spent and points of confusion

Every confusion you note becomes a fix before the module is marked stable. Export it from the progress page and attach it to an issue.