Linear Classification
From predicting numbers to predicting labels. Why fitting a line to 0/1 targets fails, how decision-boundary geometry works, and the three classifiers that replace it — the perceptron, logistic regression, and softmax — all sharing one gradient.
01 · Motivation
Why regression is not enough
In Chapter 02 we predicted continuous numbers — prices, temperatures, blood pressure — where the output could be any real number and Gaussian noise made least squares the natural fit. But a huge slice of machine learning asks a different question: which bucket does this input belong to? Not “how much” but “which one.”
That is classification. And it turns out that pointing the linear-regression machinery straight at the problem — fitting a line to 0/1 labels — fails in two quietly catastrophic ways. This chapter shows what goes wrong and introduces the principled alternatives that replaced it.
Medical diagnosis
Given a tumour’s measurements, is it malignant or benign? The answer is a label, not a number — a regression output of or has no medical meaning.
Spam detection
A message is spam or not. You could set spam , ham , fit a line and threshold at — but points deep in the “very spammy” regime drag the threshold the wrong way.
Digit recognition
A handwritten digit belongs to exactly one of ten classes. The output must express competition between classes, not an unconstrained real number.
The two failure modes of naive regression
Suppose you have binary labels , fit a least-squares line , and predict class whenever . This works in easy cases — so where does it break?
Failure 1 — outlier sensitivity
A point that is clearly class 1 but far from the boundary (predicted value ) incurs a large residual . Least squares reduces it by rotating the boundary toward the outlier, misclassifying perfectly sensible points nearby.
Failure 2 — wrong noise model
Least squares is the MLE under Gaussian noise (Ch. 02). But is Bernoulli, not Gaussian. Maximising the wrong likelihood gives biased estimates and outputs outside that cannot be read as probabilities.
The core insight of this chapter
Classification needs a model that respects the discrete, competitive nature of class labels. The fix is a nonlinear activation function — a “squashing” layer that maps any real-valued score to a valid class probability. Everything else in the chapter flows from this one design decision.
Three strategies — a navigation map
Every linear classifier here belongs to one of three families. Understanding each family’s philosophy matters more than memorising any single formula.
① Discriminant function
Learns a mapping directly, without modelling probabilities. The decision boundary is the primary object. Examples: linear discriminant, perceptron, SVM.
② Probabilistic discriminative
Models directly — calibrated probabilities without modelling the data distribution. Examples: logistic regression, softmax regression.
③ Probabilistic generative
Models the joint and derives the posterior via Bayes. Can generate new data. Examples: Gaussian discriminant analysis, Naive Bayes.
Chapter scope — and a recurring exam question
This chapter covers approaches 1 and 2 in depth; generative models (approach 3) appear in a later chapter on Gaussian classifiers. The discriminative vs. generative distinction is asked almost every year — know what each models, how many parameters it needs, and whether it yields calibrated probabilities.
02 · Intuition
Decision boundaries as fences in feature space
Scatter two classes of points on a plane. Your job is to draw a fence separating them as cleanly as possible. A linear classifier draws a straight fence — a line in 2-D, a plane in 3-D, a hyperplane in higher dimensions.
The fence is the set where . Points on one side give (class 1); points on the other give (class 2). Two knobs control it:
- — the weight vector. It points perpendicular to the fence, toward increasing . Rotating rotates the fence.
- — the bias. It shifts the fence toward or away from the origin without rotating it.
The ruler and its position
is like the angle of a ruler — which way the fence faces. is like the ruler’s position on the desk — where the fence sits. Two completely independent controls: one for orientation, one for location. That separation drives the geometry in §3.
Why the activation must be nonlinear
The fence is perfectly linear in . But we wrap that score in a nonlinear activation — why? Because we want the output to be a probability, bounded in , not an arbitrary real number. The logistic sigmoid is the standard choice:
This is the essence of a generalised linear model: the prediction is a nonlinear function of a linear combination of the inputs. The boundary is still a linear hyperplane, but the probability output is curved and bounded.
Encoding class labels
Before any formula we need a convention for representing classes as numbers — and the right choice depends on the algorithm.
Binary {0, 1}
Class 1 , class 2 . Convenient for logistic regression: the target reads directly as a target probability, and the cross-entropy loss has a clean form.
Bipolar {+1, −1}
Class 1 , class 2 . The perceptron uses this to check whether and share a sign: a misclassified point has .
Multi-class: 1-of-K (one-hot) encoding
For classes use a target vector with exactly one . If the true class is and , then . The is a flag for the winning class — nothing more. Softmax uses this encoding.
Escaping linearity with basis functions
Exactly as in linear regression (Ch. 02), we can replace the raw inputs with a nonlinear feature map . The model is then linear in -space, which means:
- The decision boundary is a hyperplane in -space.
- Mapped back to -space, that same hyperplane is a curved surface.
- So a “linear” classifier can carve arbitrarily complex boundaries in the original space.
The bridge to Chapter 02
The mechanics are identical to linear regression: the same design matrix , the same weight vector , the same linear algebra. Only the loss and the activation change. The architecture is reused; only the output layer and training objective are new.
03 · Formalism
Three blocks of theory
The formalism splits into three self-contained blocks, each a different answer to “how do we learn a decision boundary?“
- x
- an input vector in ; or its feature map .
- w
- the weight vector; with the convention , the bias folds in.
- w₀
- the bias (threshold weight) — sets the location of the decision surface.
- t
- the target label: for logistic, for the perceptron, 1-of-K for softmax.
- y
- the model output: a score, a hard label, or a probability, depending on the method.
- σ
- the logistic sigmoid .
A · Discriminant functions
The simplest classifier assigns every input to one of two classes via a single linear function:
The decision surface is the set — a hyperplane in .
Geometry — is orthogonal to the surface. Take any two points on the surface, so . Subtracting, — so is perpendicular to every vector lying in the surface. is the surface’s normal. Projecting the origin onto the surface, its signed distance from the origin is
The perpendicular foot
Any input decomposes as , where lies on the surface and is the signed perpendicular distance to the fence. So is literally how far you are from the boundary, scaled by .
Multi-class — the -class solution. Two naive extensions both fail by creating ambiguous regions:
One-vs-Rest (OvR)
Train binary classifiers, each separating one class from all others. A point can be claimed by several classes at once — or by none. Regions near boundaries are genuinely ambiguous.
One-vs-One (OvO)
Train pairwise classifiers. Voting can tie, and pairwise verdicts can be inconsistent (A beats B, B beats C, C beats A).
The clean fix is a single set of linear discriminants with an argmax rule:
One weight vector per class; the winner is whichever discriminant scores highest. No ties, no gaps.
Exam-relevant proof Why the K-class regions are provably convex
The decision region for class is . Take any two points and any . By linearity of each discriminant,
Since and for every , the same convex combination of those strict inequalities gives at the midpoint. So the midpoint is also in — the region is convex and singly connected. Equivalently, each pairwise condition rearranges to , a half-space; is an intersection of half-spaces, and an intersection of half-spaces is convex by construction.
Least squares for classification. With 1-of-K targets you can stack all class weights into a matrix and solve in closed form — the exact machinery of Ch. 02:
Why least-squares classification breaks
Two failures remain. First, OLS penalises correct, confident predictions: a point with when the target is still pays , pulling the boundary toward confident points. Second, the Gaussian noise assumption is violated for binary targets, so outputs stray outside and can’t be read as probabilities. The same two failures from §1, now formal.
B · The perceptron
The perceptron (Rosenblatt, 1958) is the oldest linear classifier and the ancestor of every neural network. It is an online algorithm: it processes one point at a time and updates immediately on each mistake, replacing the smooth sigmoid with a hard step — trading probabilities for simplicity.
The step (Heaviside) activation outputs hard labels — no probability, no confidence.
Why not just minimise mistakes? The natural 0/1 loss (count misclassifications) is piecewise constant in — flat over whole regions, then jumping. A flat function has zero gradient almost everywhere, so gradient descent cannot move. The perceptron’s fix is a piecewise-linear surrogate that grows with the distance of each misclassified point from the boundary:
is the currently misclassified set. For those points , so — a non-negative loss. Correctly classified points contribute nothing.
Stochastic gradient descent on , one misclassified point at a time, gives the famous update:
The step pushes in the direction that would correct this mistake. The learning rate can be set to without loss of generality — the solution set is invariant to scaling .
Perceptron Convergence Theorem
If the training data is linearly separable in feature space (some classifies every point), the perceptron converges to an exact solution in a finite number of updates. If the data is not separable, it cycles forever — and crucially, you cannot tell “slow convergence” from “non-convergence” by watching it run. The only safe test is to prove separability.
The perceptron’s limitations are the price of that simplicity: no probabilistic output (hard ); the solution is not unique (initialisation- and order-dependent); and on non-separable data it never converges at all.
C · Probabilistic discriminative models
Instead of a hard boundary, logistic regression models the posterior probability directly with the sigmoid:
The score is the log-odds (logit): . The boundary is exactly where the odds are 1:1, i.e. .
So logistic regression fits a linear model to the log-odds. We derive its training loss by maximum likelihood — and the gradient that drops out is the punchline of the chapter.
1 · Bernoulli likelihood
Each label is Bernoulli with success probability :
2 · Negative log-likelihood = cross-entropy
Take of the likelihood (MLE minimise this):
This is the cross-entropy loss.
3 · Chain rule
With ,
4 · The two factors
5 · The miracle cancellation
The cancels exactly:
6 · The gradient
A clean prediction-minus-target, times feature form — with no closed-form solution, because is nonlinear.
The 'same form as linear regression' is no coincidence
Compare the OLS gradient from Ch. 02: — algebraically identical. This is the exponential family at work: both Gaussian (regression) and Bernoulli (logistic) are exponential-family distributions, and for any generalised linear model the gradient of the negative log-likelihood factors as . The maths is telling you something deep: error predicted actual, regardless of output type.
Logistic regression’s properties follow from that gradient: no closed form (iterate with gradient descent, Newton–Raphson, or L-BFGS); the loss is strictly convex, so there are no local minima; outputs are calibrated probabilities; and it is outlier-robust via saturation — a confident, correct point has , so the sigmoid stops caring and the outlier barely pulls.
Multiclass — softmax. For classes, generalise the sigmoid to the softmax:
keeps every probability positive; the shared denominator forces the outputs to sum to . The gradient is the same prediction-error form again, now per class.
Perceptron and logistic regression share one update
Both step with . The only difference is what means: for the perceptron it is a hard — so the update is non-zero only on mistakes; for logistic regression it is a smooth — non-zero on every point, but tiny for confident correct ones. Replace with a step and logistic regression becomes the perceptron.
Summary — what is each method optimising?
| Method | Objective | Output | Closed form? |
|---|---|---|---|
| Least-squares classifier | real-valued score | Yes (normal equations) | |
| Perceptron | hard label | No (online SGD) | |
| Logistic regression | probability in | No (iterative, convex) | |
| Softmax regression | probability vector | No (iterative, convex) |
Only the wrong-for-the-job least-squares method has a closed form. The probabilistically principled methods need iteration — but convexity guarantees they reach the global optimum. The perceptron is the odd one out: not closed-form, not smooth-convex, yet finite-step convergent when the data cooperates.
04 · Worked example
Logistic regression by hand
We run two full gradient-descent steps on a tiny 2-D dataset — every number explicit, no black boxes.
1 · The toy dataset
Four points, two per class, with features augmented by a leading to absorb the bias:
| Point | ||||
|---|---|---|---|---|
| 1 | 1 | 1 (C₁) | ||
| 2 | 1 | 1 (C₁) | ||
| 1 | 2 | 0 (C₂) | ||
| 2 | 2 | 0 (C₂) |
Class 1 has ; class 2 has . The natural separator is the horizontal line , so we expect to grow negative and to grow positive.
2 · Step 1 — forward pass from w = 0
Initialise , learning rate . Then and for all :
| Point | ||||
|---|---|---|---|---|
| 0 | 0.500 | 1 | ||
| 0 | 0.500 | 1 | ||
| 0 | 0.500 | 0 | ||
| 0 | 0.500 | 0 |
3 · Gradient and first update
Sum the prediction-error contributions :
Only moved, becoming negative — exactly as predicted.
4 · Why didn't w₁ move?
Both classes share the same values — so carries zero information about the class. The component of the gradient is , and the symmetry cancels it to exactly zero. The optimiser is correctly inferring that is an irrelevant feature.
5 · Step 2 — second forward pass and update
With : the C₁ points () get ; the C₂ points () get . The new gradient and update:
6 · Interpreting the result
After two steps : is negative (correctly discounting high ), slightly positive, and — nearly zero, since the true boundary has no dependence. The boundary gives — still far from the true , but heading the right way. Gradient descent makes slow, steady progress.
Optional Bonus: a perceptron trace that converges in one step
Take a 1-D separable set with targets and features : point with , point with . Start at .
- Check A: — misclassified. Update: .
- Re-check A: ✓.
- Check B: ✓.
Converged in one update — the data was linearly separable in -space.
05 · Visual explanation
Four diagrams that make it click
The geometry of a decision boundary
points perpendicular to the boundary, into the half-space; slides the boundary along without rotating it, at signed distance from the origin.
The three approaches at a glance
The same problem, three philosophies — what each models, outputs, and trades off.
Discriminant — e.g. perceptron
Models: class, directly. Output: hard label. Pro: fast, simple. Con: no probability. (covered in Ch. 03)
Discriminative — e.g. logistic
Models: directly. Output: probability in . Pro: fewer parameters than generative. Con: can’t generate data. (covered in Ch. 03)
Generative — e.g. Gaussian DA
Models: and . Output: posterior via Bayes. Pro: can generate data, handle missing inputs. Con: more parameters, harder fit. (later chapter)
Sigmoid vs. step
The logistic sigmoid is the smooth, differentiable cousin of the perceptron’s step. Both cross at ; replace with the step and logistic regression becomes the perceptron.
The softmax probability simplex
For three classes, every prediction is a point inside a triangle: the corners are pure classes, the centroid is the uniform , and every interior point sums to .
Why least squares fails on classification
With no outliers, least squares and logistic regression agree. Add a cluster of far outliers and least squares rotates its boundary to shrink their squared residuals, wrecking the bulk fit — while logistic regression barely moves, because the sigmoid saturates and the outliers contribute almost no gradient.
06 · Hands-on
Try it yourself
Four labs, each drilling one idea you need to see move before it sticks. Push the controls, watch the numbers, then read the takeaway.
Decision boundary explorer
Drag the sliders to move and rotate the fence y = w₁x₁ + w₂x₂ + w₀ = 0. Points the boundary gets wrong glow amber; the gold arrow is w, always perpendicular to the line and pointing into the y > 0 half-space.
Perceptron step-through
Each Next step applies one update w ← w + φ(xₙ)·tₙ on the first misclassified point (glowing amber, with learning rate α = 1). The data is linearly separable, so the perceptron is guaranteed to reach zero mistakes in finite steps.
Logistic regression live fit
Gradient descent fits σ(wᵀφ) in real time. Raise class noise to overlap the blobs, or add a far outlier (a wrong-class point flung into the opposite territory) and watch how little the boundary flinches.
Softmax probability explorer
Adjust the three raw scores a₁, a₂, a₃. Softmax exponentiates and normalises them into probabilities that always sum to 1 — so the classes compete. The dot on the simplex is the resulting (p₁, p₂, p₃).
07 · Exam intel
What examiners actually test
Three approaches — know when to use which
Discriminant (perceptron): maps straight to a label, no probabilities, fast. Discriminative (logistic): models directly — fewer parameters than generative, calibrated probabilities, the gold standard. Generative (Gaussian DA): models and , derives the posterior via Bayes, can generate data. Exam pattern: “compare discriminative and generative” — state what each models, parameter count, and whether it gives calibrated probabilities.
The logistic-regression gradient — the gift
has the same algebraic form as the least-squares gradient — a consequence of the exponential family, not a coincidence. Examiners test: (i) no closed form, since is nonlinear; (ii) the loss is strictly convex, so the global minimum is guaranteed; (iii) gradient descent, Newton–Raphson, and L-BFGS all apply.
Perceptron Convergence Theorem
Statement: if the data is linearly separable in feature space, the perceptron converges in finitely many steps to an exact solution. Caveat: if it is not separable, the algorithm never converges — and you cannot tell slow from non-convergent from the outside. can be set to 1: the update is invariant to scaling , so the learning rate is immaterial to the solution set.
Softmax gradient — same pattern again
For multi-class cross-entropy, . The derivation hinges on the softmax Jacobian ; multiply by the cross-entropy term and sum over and it collapses to . Memorise the Jacobian — exams ask you to derive this.
Four formulas to memorise
- Sigmoid: , with .
- Cross-entropy: .
- Logistic gradient: .
- Softmax: .
08 · Common mistakes
Traps to avoid
Regression loss ≠ classification loss
Sum-of-squares on binary targets is wrong twice over: it assumes Gaussian noise (labels are Bernoulli), and it penalises correct, confident predictions ( for pays ), pulling the boundary toward outliers. Always use cross-entropy for classification.
The boundary is linear — the model is not
Logistic regression’s boundary reduces to , a linear hyperplane. But the probability output is nonlinear in the inputs. On an exam, always say what is linear (the boundary / logit) and what is nonlinear (the probability).
Perceptron ≠ logistic regression
They share the update , so they look identical on the board. But the perceptron uses a hard label with no probabilistic loss and a finite-step convergence theorem (only if separable); logistic regression has calibrated probabilities, a cross-entropy loss, and converges to a unique global minimum even on non-separable data.
Softmax ≠ K independent sigmoids
Applying to each score separately, , gives outputs that do not sum to 1 — not a valid distribution. Softmax normalises globally, , forcing and making the classes compete: raising lowers every other .
The class-imbalance blind spot
With 95% class-A data, “always predict A” scores 95% accuracy and is useless. Cross-entropy does not automatically protect you — the boundary can collapse to one side while the loss still drops. Monitor per-class recall and the boundary’s position, not just overall accuracy.
Linear in feature space ≠ linear in input space
“Linear classifiers can’t solve XOR” is true only in the raw input space. With the right basis (e.g. ), a linear classifier in -space draws a nonlinear boundary in -space — and solves XOR trivially.
Convergence does not mean uniqueness
The Perceptron Convergence Theorem guarantees the algorithm finds a separating hyperplane — not the best one. Different initialisations and orderings give different solutions, all with zero training error but different generalisation. No margin guarantee (that is the SVM, Ch. 7).
09 · Self-check
Can you answer these?
Seven questions mirroring how the chapter gets tested. Click an option for instant feedback.
What are the two failure modes of using ordinary least squares for binary classification?
In the linear discriminant y(x) = wᵀx + w₀, what geometric role does w₀ play?
State the exact condition under which the Perceptron Convergence Theorem applies.
Write the gradient of the logistic cross-entropy loss. Why is the result described as surprising?
You apply K independent sigmoids pₖ = σ(wₖᵀφ) instead of a softmax. What is the fundamental problem?
A classmate says: 'Linear classifiers can never solve XOR because XOR is not linearly separable.' Is this correct?
For the K-class argmax rule (assign x to Cₖ iff yₖ(x) > yⱼ(x) for all j ≠ k), why are the decision regions convex?
10 · Recap
One-screen summary
Chapter 03 — load-bearing ideas
- Regression is not classification. Fitting a line to targets fails twice: outlier sensitivity and a violated Gaussian-noise assumption. The fix is a nonlinear, probability-valued activation.
- Three strategies: discriminant (boundary first), probabilistic discriminative ( directly), probabilistic generative (model the joint, invert with Bayes). This chapter does the first two.
- Boundary geometry. is the normal — it sets orientation; sets position, at signed distance from the origin. is the perpendicular distance.
- The -class rule. A single set of discriminants with argmax gives convex, gap-free regions — beating one-vs-rest and one-vs-one, which both leave ambiguous zones.
- Perceptron. Online updates on misclassified points only; converges in finite steps iff separable; no probabilities, non-unique, order-dependent; can be .
- Logistic regression. is a calibrated posterior; cross-entropy is the ML loss; the gradient matches linear regression’s — exponential-family structure. No closed form; strictly convex.
- Softmax generalises to classes; outputs always sum to and compete globally, which is why independent sigmoids are wrong.
- One update, two algorithms. Perceptron and logistic regression step identically; swapping the step for a sigmoid turns one into the other.
Looking ahead → Chapter 04
Given several classifiers, how do we pick the best without overfitting? The bias–variance tension from Ch. 02 returns — a logistic model with too many basis functions overfits just like a high-degree polynomial. Cross-validation, regularisation, and information criteria are next.