Legacy: logistic, softmax, SVM

Older material, kept last

8 lessons · 20 past questions · 49 marks in the papers collected here

Open the interactive lessons →Legacy: logistic, softmax, SVM past questions

Diagrams, animations, quizzes and checked solutions are on the interactive pages.

Contents

  1. Orientation: what you will learn and why
  2. Big picture: concept map, comparison table and the recipe
  3. Start here: signs, the sigmoid and logs
  4. Linear classifiers: geometry and separability
  5. Logistic regression: probability, loss, update, threshold
  6. Softmax regression for many classes
  7. Hard-margin SVM: the biggest safe margin
  8. Soft-margin SVM: slack variables and accuracy

1. Orientation: what you will learn and why

This older material is about classification with a straight boundary. A linear classifier splits the space by a line (a plane in more dimensions). Logistic and softmax regression turn the distance from that line into a probability; the support vector machine (SVM) chooses the line with the biggest safety margin. It is kept last because it matters less for Quiz 2 than the earlier topics, but it still appears in past papers.

What you will be able to do

Why this topic matters for Quiz 2

Counted only from the PYQs in this project (not a prediction):

What the PYQs askPYQsMarks
Linear separability and boundary geometry415
Logistic regression614
Softmax regression37
Hard-margin SVM24
Soft-margin SVM, slack and accuracy59

In total 20 PYQs worth 49 marks across 4 papers (11 MCQ, 5 MSQ, 4 numeric). Most of the logistic, softmax and SVM questions come from one 2022 paper.

How this topic connects

The linear form $w^Tx$ is the same as in linear regression. Kernels (earlier topic) are the way to make SVM boundaries curved.

Tags: [SRC] from your files, [DERIVED] answer I worked out because the bank gives no key, [ADDED] my own example, [FLAG] disagreement between my calculation and a key.
How to use this page

Read each section, do the quick checks, then attempt each PYQ before opening its solution. Figures are described in words; where the bank gives coordinates they are used.

What is new in this upgrade [ADDED]

2. Big picture: concept map, comparison table and the recipe

[ADDED] Read this page first. Logistic regression, softmax and SVM all start from the same score.

The concept map

Score z = w^T x + bsign = side of the lineLogisticsigmoid(z): probability, cross-entropySoftmaxK scores: probabilities sum to 1SVMwidest margin; slack if overlappingAll three draw a straight boundary. They differ in the loss they minimise:cross-entropy (logistic, softmax) versus hinge loss with a margin (SVM).
One score, three classifiers: sigmoid gives a probability, softmax gives K probabilities, the SVM maximises a margin.

Comparison [ADDED]

LogisticSoftmaxHard-margin SVMSoft-margin SVM
Classes2$K$22
Output$P(y=1\mid x)$$K$ probabilities, sum $1$a side of the linea side of the line
Losscross-entropycross-entropy$\tfrac12\|w\|^2$ with constraints$\tfrac12\|w\|^2+C\sum\xi_i$
Needs separable data?nonoyesno
Parameter shape$w\in\mathbb R^d$$W\in\mathbb R^{d\times K}$$w,b$$w,b,\xi$

Mnemonics and recognition cues [ADDED]

Analogy and its limit [ADDED]

AnalogyGood forWhere it breaks
Fence between villages (SVM)why the widest street is the safest boundaryonly the nearest houses (support vectors) matter, unlike the fence story where every house seems to count

Recall questions

$\sigma(0)$?

$0.5$.

Shape of $W$ for $d=5$ features, $K=3$ classes?

$5\times3$.

3. Start here: signs, the sigmoid and logs

Piece 1. The score $w^Tx+b$

$w^Tx+b=w_1x_1+\dots+w_dx_d+b$ is a number called the score. Its sign tells which side of the boundary $w^Tx+b=0$ the point is on.

Piece 2. The sigmoid

Formula: sigmoid

$$\sigma(z)=\frac1{1+e^{-z}}$$ $z$ is any real number; $\sigma(z)$ is always between $0$ and $1$, equals $0.5$ at $z=0$ and increases with $z$.

Piece 3. Logarithms of probabilities

For $0<p<1$, $-\log p$ is positive, large when $p$ is small and $0$ when $p=1$. This is why $-\log p$ works as a "cost of being wrong".

Worked example: sigmoid values and their losses

$\sigma(2)=\dfrac1{1+e^{-2}}=0.881$ and $\sigma(-2)=0.119$; they add to $1$ because $\sigma(-z)=1-\sigma(z)$. If the true label is $1$, the loss is $-\ln p$: $-\ln0.881=0.127$ (confident and right, small) but $-\ln0.119=2.13$ (confident and wrong, large).

4. Linear classifiers: geometry and separability

Intuition

Everyday analogy

Draw a fence (line). Everything on one side is labelled $+$, the other side $-$. The vector $w$ is like an arrow standing perpendicular to the fence and pointing toward the $+$ side.

Definition: Linear classifier

Predict $+1$ if $w^Tx+b>0$ and $-1$ (or $0$) otherwise. The boundary is the set $w^Tx+b=0$. The vector $w$ is perpendicular to the boundary and points toward the positive side.

Formula: Signed distance

$$\text{signed distance of }x=\frac{w^Tx+b}{\|w\|}$$ Positive on the $w$-side, $0$ on the boundary, negative on the other side. So $w^Tx$ (with $b=0$) grows as a point moves further in the direction of $w$.

Linear separability

A data set is linearly separable if some line puts all $+$ points on one side and all $-$ points on the other.

Worked examples

Worked example: Simple: points along one direction

Problem. Data $\{(-v,1),(-3v,1),(v,0),(2v,0)\}$ with $v\ne0$ and labels in $\{0,1\}$; predict $1$ when $w^Tx>0$.

What is asked. The condition on $w^Tv$ for zero training mistakes.

Idea / formula used. Write the score of each point.

Scores: $-w^Tv,\;-3w^Tv,\;w^Tv,\;2w^Tv$.
Label-1 points need score $>0$: $w^Tv<0$.
Label-0 points then have negative scores, which is allowed ($\le0$).
Answer: $w^Tv<0$
Common mistake: assuming $w$ must point along $v$.
Worked example: Exam level: which datasets are separable (coordinates given)

Problem. Red ($-1$) and green ($+1$): Dataset 3: red $(-2,1),(1,-2)$; green $(-0.5,1),(1,1)$. Dataset 4: red $(-1,1),(2,1)$; green $(-1,-1),(1,-2)$. Dataset 1 (XOR): red $(-1,1),(1,-1)$, green $(1,1),(-1,-1)$. Dataset 2: green $(0,0)$ inside red $(\pm1,\pm1)$.

What is asked. The separable datasets.

Idea / formula used. Search for a separating line.

Dataset 1: any line leaves two diagonal points on the wrong side; not separable (checked by searching all directions: best gap $-1.414$ is negative).
Dataset 2: the centre point is inside the convex hull of the four red points, so no line separates it: not separable (gap $-1.000$).
Dataset 3: a separating direction exists (gap $1.061$ is positive): separable.
Dataset 4: a horizontal line $x_2=0$ puts both reds above and both greens below: separable (gap $2.000$).
Answer: Datasets 3 and 4
Common mistake: judging by symmetry instead of testing for a line.
Worked example: Tricky: ordering of scores from positions

Problem. A boundary through the origin has $w$ as its normal. $P,Q,R$ lie on the side $w$ points to, $P$ farthest from the boundary and $R$ nearest. $S$ lies on the boundary. $T,U$ lie on the other side, $U$ farther.

What is asked. Order all six scores.

Idea / formula used. A score is signed distance along $w$ times $\|w\|$.

On the boundary: $w^TS=0$.
Positive side, by distance: $0
Other side: farther means more negative: $w^TU
Answer: $w^TU
Common mistake: ordering by distance from the origin instead of from the boundary.

Separable or not: a quick test [ADDED]

PatternSeparable by one line?Why
two blobs apartyesa line fits between
XOR (opposite corners share a label)noany line leaves a point on the wrong side
one class inside a ring of the othernoa line cannot enclose
all points on a line, labels alternatenoa single threshold cannot alternate
Is XOR linearly separable?

No.

5. Logistic regression: probability, loss, update, threshold

Intuition

Everyday analogy

The score $w^Tx$ is a "confidence meter". The sigmoid squashes it into a probability: far on the positive side means near $1$, far on the negative side near $0$, on the boundary exactly $0.5$.

Formula: Logistic model

$$P(y=1\mid x)=\sigma(w^Tx)=\frac1{1+e^{-w^Tx}}$$ $w$ are the weights (a dummy feature $1$ can carry the bias). The predicted class is $1$ when this probability exceeds the threshold (default $0.5$, i.e. $w^Tx>0$).

Formula: Binary cross-entropy loss

$$L(w)=\sum_{i:\,y_i=1}-\log p_i\ +\sum_{i:\,y_i=0}-\log(1-p_i),\qquad p_i=\sigma(w^Tx_i)$$ A point of class $1$ costs $-\log p_i$ (small if $p_i$ is near $1$); a point of class $0$ costs $-\log(1-p_i)$.

Formula: Gradient descent update

$$w\leftarrow w-\alpha\,X^T\big(\sigma(Xw)-y\big)$$ with $X$ the $n\times m$ feature matrix (one row per point), $y$ the $n$ labels and $\alpha$ the learning rate. The error vector $\sigma(Xw)-y$ is multiplied by $X^T$ and we move against the gradient (minus sign).

Worked examples

Why the update is $(y-p)\,x$, for one point

Loss $L=-[y\ln p+(1-y)\ln(1-p)]$ with $p=\sigma(w^Tx)$. The sigmoid’s slope is $p(1-p)$, so $\dfrac{\partial L}{\partial w}=\left(-\dfrac yp+\dfrac{1-y}{1-p}\right)p(1-p)\,x=(p-y)\,x$. Going downhill gives $w\leftarrow w+\eta\,(y-p)\,x$.

Numbers: $w=(0,0)$, $x=(2,1)$, $y=1$, $\eta=1$. Then $p=0.5$, the new $w=(1,0.5)$, and $p$ rises to $\sigma(2.5)\approx0.92$.

Worked example: Simple: probabilities rise with the score

Problem. $w=(1,1)$, points $(-3,-3),(-0.5,-0.3),(0.5,0.3),(2,2)$ (ordered along $w$). Probabilities?

What is asked. The ordering of $p$.

Idea / formula used. $p=\sigma(w^Tx)$.

Point 1: $z=-6.0$, $p=0.002$.
Point 2: $z=-0.8$, $p=0.310$.
Point 3: $z=0.8$, $p=0.690$.
Point 4: $z=4.0$, $p=0.982$.
The probabilities increase with the score; the point furthest on the negative side has the smallest $p$.
Answer: $p_1<p_2<p_3<p_4$
Common mistake: thinking the point furthest from the boundary has the largest probability regardless of side.
Worked example: Exam level: the loss of a labelled set

Problem. Points $1,2,3$ have class $0$ and points $4,5$ class $1$; the model gives $p=(0.2,0.1,0.5,0.9,0.6)$.

What is asked. The total log loss.

Idea / formula used. Class 1 pays $-\ln p$, class 0 pays $-\ln(1-p)$.

Class 0: $-\ln0.8-\ln0.9-\ln0.5=0.223+0.105+0.693$.
Class 1: $-\ln0.9-\ln0.6=0.105+0.511$.
Add all five.
Answer: about $1.64$
Common mistake: using $-\ln p$ for every point.
Worked example: Tricky: the threshold for a safety-critical detector

Problem. A video detector must catch almost all objectionable videos (positive class); false alarms are acceptable. Should the threshold be high or low?

What is asked. The threshold choice.

Idea / formula used. Predict positive when $p\ge\text{threshold}$.

A lower threshold predicts positive for more videos, so fewer positives are missed.
The price is more harmless videos flagged, which is acceptable.
Answer: Low threshold
Common mistake: choosing a high threshold, which misses positives.

Which features give a circular boundary?

A circle $(x_1-a)^2+(x_2-b)^2=r^2$ expands to $x_1^2+x_2^2-2ax_1-2bx_2+(a^2+b^2-r^2)=0$. A linear function of the features can represent it only if the features include $1$, $x_1$, $x_2$, $x_1^2$ and $x_2^2$. Without $x_1,x_2$ the circle must be centred at the origin; without the constant $1$ it must pass through the origin.

Loss on correct predictions

Even with $100\%$ accuracy the loss is not $0$: every $p_i<1$. Points far from the boundary have $p_i$ close to the true label, so their loss is small; points near the boundary have $p_i$ near $0.5$ and a larger loss. So correctly classified points far from the boundary give a smaller loss than correctly classified points close to it.

Trap: update sign and shape

Gradient descent subtracts: $w\leftarrow w-\alpha X^T(\sigma(Xw)-y)$. Using $Xw-y$ (without sigmoid) is linear regression, and $X$ (not $X^T$) would not have the right dimensions.

The sigmoid, drawn [ADDED]

00.51-5-4-3-2-10123450.1190.5000.881score z = w^T xP(y = 1 | x) = sigma(z)
$\sigma(2)=0.881$ and $\sigma(-2)=0.119$ add to $1$: the curve is symmetric about $(0,0.5)$.

Hinge loss next to logistic loss [ADDED]

-2-1012340123hinge: max(0, 1 - m)logistic: log(1 + e^-m)margin m = y (w^T x + b)
Both losses fall as the margin $m=y(w^Tx+b)$ grows. Hinge is exactly $0$ once $m\ge1$; logistic never reaches $0$. This is why only support vectors matter for the SVM.
$z=-2$: probability of class 1?

$0.119$.

6. Softmax regression for many classes

Intuition

Everyday analogy

Logistic regression answers yes/no. Softmax is a multiple-choice question: it scores every class and turns the scores into probabilities that add up to $1$.

Formula: Softmax

$$P(y=c\mid x)=\frac{e^{w_c^Tx}}{\sum_{j=1}^Ke^{w_j^Tx}}$$ $K$ is the number of classes and $w_c$ the weight vector of class $c$. The $K$ numbers are positive and sum to $1$.

Formula: Weight matrix shape

$$W\in\mathbb R^{d\times K}$$ $d$ rows (one per feature), $K$ columns (one per class). Column $c$ holds the weights for class $c$.

Worked examples

Worked example: Simple: is this a probability vector?

Problem. Which can be a softmax output: $[0.5,0.3,0.2]$, $[0.7,0.4,-0.1]$, $[0.25,0.25,0.25,0.25]$, $[0.6,0.6,0.1]$?

What is asked. The valid vectors.

Idea / formula used. Every entry is positive and the entries sum to $1$.

First: sums to $1$, all positive.
Second: sums to $1$ but has a negative entry.
Third: valid, four equal classes.
Fourth: sums to $1.3$.
Answer: the first and third
Common mistake: checking only the sum.
Worked example: Exam level: dimension of $W$

Problem. $4$ classes, $7$ features, bias handled separately.

What is asked. The shape of $W$, and what its second row holds.

Idea / formula used. $W$ is $d\times K$.

$d=7$ rows and $K=4$ columns.
A column belongs to a class; a row belongs to a feature.
Answer: $7\times4$; row 2 holds feature 2's weight for each class
Common mistake: swapping rows and columns.
Trap: rows vs columns

Rows go with features, columns with classes (in this convention $W$ is $d\times K$).

A worked softmax [ADDED] (not a PYQ)

Scores $z=(2,1,0)$ for three classes. Exponentials $e^2,e^1,e^0$, normalised:

ClassScoreProbability
120.6652
210.2447
300.0900

They add to $1.0000$. The largest score gets the largest probability, and adding the same constant to every score changes nothing.

Can softmax output $(0.5,0.6,-0.1)$?

No: a negative entry and the sum is not 1.

7. Hard-margin SVM: the biggest safe margin

Intuition

Everyday analogy

Many fences separate two villages. The safest fence is the one furthest from both villages: it keeps the widest empty street between them.

Definition: Hard-margin SVM

For separable data with labels $y_i\in\{-1,+1\}$, choose the line $w^Tx+b=0$ that maximises the margin (the width of the empty strip), subject to every point being on the correct side beyond the strip.

Formula: Hard-margin problem

$$\min_{w,b}\ \tfrac12\|w\|^2\quad\text{subject to}\quad y_i(w^Tx_i+b)\ge1\ \text{ for all }i$$ The margin width is $2/\|w\|$, so minimising $\|w\|$ maximises the margin. $y_i(w^Tx_i+b)\ge1$ says point $i$ is on its correct side and at least the margin edge away.

Worked examples

Worked example: Simple: who satisfies the constraint?

Problem. $w=(1,1)$, $b=-3$. Points: $A=(1,0)$ with $y=-1$, $B=(3,2)$ with $y=+1$, $C=(2,1.5)$ with $y=+1$.

What is asked. Which satisfy $y(w^Tx+b)\ge1$?

Idea / formula used. Compute the score, then multiply by the label.

$A$: score $-2$, product $2$: satisfied.
$B$: score $2$, product $2$: satisfied.
$C$: score $0.5$, product $0.5$: correct side but inside the margin.
Answer: $A$ and $B$
Common mistake: calling $C$ fine because it is classified correctly.
Worked example: Why the margin width is $2/\|w\|$

Problem. $w=(3,4)$, $b=-5$.

What is asked. The distance between the lines $w^Tx+b=-1$ and $w^Tx+b=1$.

Idea / formula used. Walk from the boundary straight along the unit vector $w/\|w\|$.

$\|w\|=5$. A step of length $t$ along $w/\|w\|$ changes the score by $t\,w^Tw/\|w\|=t\|w\|=5t$.
To go from score $0$ to score $1$: $5t=1$, so $t=0.2$.
The same distance reaches score $-1$ on the other side: total $0.4$.
Answer: $2/\|w\|=0.4$
Common mistake: reading the margin as $\|w\|/2$: a larger $w$ gives a narrower margin.

A hard-margin SVM, drawn [ADDED]

-10123401234f = 0 (boundary)f = +1f = -1support vector (2,2)support vector (0,0)w = (0.5, 0.5), b = -1: margin = 2/||w|| = 2.83 (blue = class +1, red = class -1)
Four points. The support vectors $(2,2)$ and $(0,0)$ sit on the margin lines. $w=(0.5,0.5)$, $b=-1$, margin $2/\|w\|=2.828$, which equals the distance between the two support vectors. The other two points could be removed or moved (staying outside the street) without changing the line.
Which points decide a hard-margin SVM?

Only the support vectors, those on the margin lines.

8. Soft-margin SVM: slack variables and accuracy

Intuition

Everyday analogy

If the villages overlap, no street is wide enough for everyone. Soft margin lets a few people stand inside the street or on the wrong side, but charges a fine proportional to how far they are over the line.

Definition: Slack variable

$\xi_i=\max\big(0,\ 1-y_i(w^Tx_i+b)\big)$: how far point $i$ violates its margin constraint. $\xi_i=0$ if the point is on or beyond its margin edge.

Formula: Soft-margin problem

$$\min_{w,b,\xi}\ \tfrac12\|w\|^2+C\sum_i\xi_i\quad\text{s.t.}\ y_i(w^Tx_i+b)\ge1-\xi_i,\ \xi_i\ge0$$ $C>0$ is the price per unit of slack: large $C$ punishes violations heavily (narrow margin), small $C$ tolerates them.

Position of a positive pointScore $w^Tx+b$Slack $\xi$
on the margin edge or beyond$\ge1$$0$
on the boundary$0$$1$
on the negative margin edge$-1$$2$
deep in negative territory$-3$$4$

Worked examples

Worked example: Simple: slack values from scores

Problem. Scores $w^Tx+b$: $P_1=2.5$, $P_2=0.4$, $P_3=-0.5$ (all class $+1$) and $N=-0.2$ (class $-1$).

What is asked. The four slack values.

Idea / formula used. $\xi=\max(0,\,1-y\cdot\text{score})$.

$P_1$: $\max(0,-1.5)=0$.
$P_2$: $0.6$ (right side, inside the margin).
$P_3$: $1.5$ (wrong side).
$N$: $y\cdot$score $=0.2$, so $0.8$.
Answer: $0,\;0.6,\;1.5,\;0.8$
Common mistake: forgetting to multiply by the label for $N$.
Worked example: Exam level: accuracy of a given SVM

Problem. $w=(2,-1)$, $b=-1$. $(x_1,x_2,y)$: $(2,1,1),(1,3,1),(3,2,1),(0,0,-1),(1,-2,-1),(-1,1,-1)$.

What is asked. The fraction predicted correctly.

Idea / formula used. Predict $+1$ when the score is positive.

Scores: $2,\;-2,\;3,\;-1,\;3,\;-4$.
Predictions: $+,-,+,-,+,-$.
Wrong: the second and fifth points.
Answer: $4/6=2/3$
Common mistake: leaving out $b$.
Worked example: Tricky: which accuracies are possible?

Problem. Three points on a line: $+$ at $0$ and $2$, $-$ at $1$. A linear classifier (threshold not at a point) is tested.

What is asked. The possible accuracies.

Idea / formula used. A threshold can only split the line into two sides.

Predictions it can make: $+++$, $---$, $+--$, $++-$, $-++$, $--+$.
It can never make $+-+$ (all correct) or $-+-$ (all wrong).
The six possible ones score $2/3,1/3,2/3,1/3,1/3,2/3$.
Answer: $1/3$ or $2/3$
Common mistake: assuming some threshold gets all three right.

Slack in four cases [ADDED]

$\xi=\max(0,1-m)$ with margin $m=y(w^Tx+b)$:

$m$PositionSlack $\xi$
2on the right side, beyond the margin0.0
1exactly on the margin edge0.0
0.4right side but inside the street0.6
-0.5wrong side1.5
A point has $y(w^Tx+b)=0.4$. Slack?

$0.6$.

What does a larger $C$ do?

Violations cost more, so the margin shrinks and fewer points violate it.

Practise this topic →

Other MLT topics