B4B33RPZ · Pattern Recognition and Machine Learning
Logistic regression
Lab 6: learning the posterior directly, the loss as a likelihood, and regularisation as a prior
Klára JanouškováFEE CTU, Prague
Warm-up: ML and MAP
A coin lands heads 3 times out of 3. The ML estimate of θ=P(heads) is…
θ^ML=NNH=33=1. ML trusts the data completely, even 3 flips. Keep this in mind: today ML will want some weights to be infinite.
MAP with a flat (uniform) prior gives…
θ^MAP=argmaxθp(D∣θ)p(θ); a constant p(θ) does not move the maximum. MAP = ML + "what we believed before". Today: that belief becomes a penalty on the weights.
Part 1
From Bayes to logistic regression
Two classes: which one do we pick?
Will a student pass the test? We know x = hours studied. Classes k∈{−1,+1}: fail / pass. With the 0/1 loss (Bayes lab), which class should q(x) say?
↓ 0/1 loss: pick the class with the larger posterior
q(x)=argkmaxp(k∣x)
↓ only two classes: compare the two posteriors through their ratio
q(x)=+1⟺p(−1∣x)p(+1∣x)>1
↓ ln is increasing, and ln1=0: ratio >1⟺ its log >0
q(x)=+1⟺a(x)=lnp(−1∣x)p(+1∣x)>0
The log-odds
Odds = "how many to one", as in betting. p=0.75 → odds 0.250.75=3 (3 : 1 for passing), a=ln3=1.1.
a>0: pass more likely; a<0: fail more likely; a=0: 50/50.
Have we seen this ratio before?
p(−1∣x)p(+1∣x) looks like the likelihood ratiop(x∣−1)p(x∣+1) from the Bayes and minimax labs. Same thing?
No. Posterior: "class given data". Likelihood: "data given class".
↓ Bayes' rule on top and bottom; p(x) is in both, it cancels
A coin: biased (P(H)=0.8) or fair (0.5)? We see one head. Likelihood ratio (data alone):
0.8/0.5=1.6
a head is 1.6× more likely with the biased coin
Priors 0.5 / 0.5: posterior odds =1.6⋅1
=1.6, so P(biased∣H)=1.6/2.6=0.62
Sceptical prior P(biased)=0.1: odds =1.6⋅0.1/0.9
=0.18, so P(biased∣H)=0.18/1.18=0.15
What if we learn a(x) directly?
So far: generative (MLE lab)
Estimate p(x∣k) and p(k) for each class, then Bayes' rule, then a(x).
A whole density per class, just to get one number per x.
Today: logistic regression
Skip the densities. Assume the log-odds is linear in x and learn its weights:
a(x)=w0+w1x1+⋯+wDxD=w⋅x
with x=(1,x1,…,xD): the extra 1 carries the bias w0.
Like a points system: every feature adds or subtracts "evidence for passing"; the weight says how much per unit.
Example: a(x)=−3+1⋅x. At x=3 h: a=0, even odds. Each extra hour adds 1 to the log-odds, i.e. multiplies the odds by e1≈2.7.
From log-odds back to a probability
We know a. What is p=p(+1∣x)? (Then p(−1∣x)=1−p.)
ln1−pp=a
↓ exponentiate both sides
1−pp=ea⇒p=ea−pea
↓ multiplied by (1−p) above; now move pea to the left and factor out p
p(1+ea)=ea⇒p=1+eaea
↓ divide top and bottom by ea
p(+1∣x)=1+e−a1=σ(a)
Example
a(x)=x−3, σ(a)=1/(1+e−a):
x=3: σ(0)=1/(1+1)=0.5
x=5: σ(2)=1/(1+e−2)=0.88
x=1: σ(−2)=1/(1+e2)=0.12
0.88 and 0.12 add up to 1: a hint for the next slide.
One formula for both classes
p(+1∣x)=σ(a). What is p(−1∣x)?
p(−1∣x)=1−σ(a)=1−1+e−a1
↓ common denominator
=1+e−a1+e−a−1=1+e−ae−a
↓ divide top and bottom by e−a
=ea+11=σ(−a)
With k∈{−1,+1} both cases are one formula:
p(k∣x)=σ(kw⋅x)
This is why the assignment uses ±1 and not {0,1}.
Part 2
The sigmoid and its weights
The logistic sigmoid
σ(a)=1+e−a1
squashes any score a∈(−∞,∞) into (0,1): a probability
σ(0)=0.5 (circle); σ(−a)=1−σ(a)
…does it look familiar? tanh(a)=2σ(2a)−1: the same S, stretched to (−1,1)
both are classic activation functions in neural networks
What do w0 and w1 do?
One feature: p(+1∣x)=σ(w0+w1x). Guess first: what happens when we change w0? And w1?
w0 shifts the curve left / right: it moves the point where p=0.5.
w1 sets the steepness: how fast the evidence grows with x. Negative w1 flips the S.
Decision boundary:p=0.5⟺a(x)=0. Where is it in 1D? That is your get_threshold.
Two features: what does the boundary look like?
a(x)=w1x1+w2x2 (here w0=0). Where is p the same?
Equal p ⇔ equal a: parallel straight lines. The boundary a=0 is a line (a plane, a hyperplane in D dimensions).
w is perpendicular to them and points to class +1. Longer w → lines closer together → a steeper, more confident model.
w0 shifts the line away from the origin.
Quick check
For one student, w⋅x=0. What is p(pass∣x)?
p(+1∣x)=σ(w⋅x)=σ(0)=1+e01=0.5: the student sits exactly on the boundary.
We replace w by −w. What happens?
σ(−w⋅x)=1−σ(w⋅x). Same boundary line, but w now points to the other class.
Part 3
Which w? The likelihood is the loss
How good is a given w?
Let the model bet on what really happened. A good w gives high probability to the true labels. Try w=(−3,1), i.e. a=x−3:
student
x (h)
true k
a=x−3
p(k∣x)=σ(ka)
Ann
1
−1 fail
−2
σ(2)=0.88
Ben
4.5
+1 pass
1.5
σ(1.5)=0.82
Cid
3.5
−1 fail
0.5
σ(−0.5)=0.38
All three right at once (independent students): multiply.
L(w)=i∏p(ki∣xi,w)
=0.88⋅0.82⋅0.38=0.27
This is the likelihood of w, exactly as for the coin last week. ML: pick the w with the largest L.
From the likelihood to a loss
L(w)=i=1∏Np(ki∣xi,w)=i=1∏Nσ(kiw⋅xi)
↓ ln: the product becomes a sum (and no tiny numbers: 0.91000≈10−46). Maximise ⟺ minimise the negative
w^ML=argwmini∑−lnσ(kiw⋅xi)
↓ −lnσ(m)=−ln1+e−m1=ln(1+e−m); dividing by N does not move the minimum
E(w)=N1i=1∑Nln(1+e−kiw⋅xi)
the assignment's loss = the (logistic) cross-entropy
Ann, Ben, Cid
−ln of each bet:
0.13+0.20+0.97=1.30
−lnL:
−ln0.27=1.30: the same
−lnp = surprise. A confident wrong bet (Cid) costs most.
What does each student cost?
Marginm=kw⋅x: positive = on the right side of the boundary, large = confident.
m=−2: wrong and confident: 2.13. Far on the wrong side the cost grows like ∣m∣.
m=0: on the boundary, "50/50": ln2=0.69.
m=2: right and confident: 0.13. Never exactly 0: still a small push to be even more sure.
Quick check
Which training example adds the most to E(w)?
Loss ln(1+e−m): m=−3 gives ln(1+e3)=3.05, m=0 gives 0.69, m=3 gives 0.05. Wrong and confident costs most.
An example is classified correctly (m>0). Can its loss be larger than 0.5?
ln(1+e−m)>0.5 for m<0.43. Right side but barely: the model was not sure, so it still pays.
Try it: find a good w by hand
Can we solve for the best w directly?
For μ of a Normal we set the derivative to 0 and solved. Can we do that for E(w)?
No closed form:w sits inside N sigmoids, the equation ∇E=0 cannot be solved by hand.
But E is convex: one bowl, no local minima. So just walk downhill.
Gradient descent: in thick fog on a hill, feel the slope under your feet and step the other way.
w←w−η∇E(w)
η: the step size (learning rate)
Homework
∇E(w): derive it with the chain rule through ln and σ (logistic_loss_gradient).
How big should the step be?
too small: safe, but many steps
just right: a few steps to the bottom
too large: jumps over the minimum and can diverge. The assignment adapts η (next slide).
Gradient descent in the assignment
# input: x (observations), k (labels), w_init
w = w_init
step_size = 1.0
E, g = compute_E_and_gradient(x, k, w)
while not TERMINATION_CONDITION:
E_new, g_new = compute_E_and_gradient(
x, k, w - step_size * g)
if E_new < E: # success
w -= step_size * g
g, E = g_new, E_new
step_size *= 2
else:
step_size /= 2
return w
Accept a step only if E decreases. If not, the step was too large (halve it) or we are already at the optimum.
After a success, try a bigger step (double it).
The gradient is normalised by N (E is a mean), otherwise its size grows with N and you would need smaller steps for more data.
Stop when ∥wnew−wprev∥≤ε.
Try it: gradient descent on the students
Part 4
Why is it called cross-entropy?
Where have we seen −lnp before?
We already have the loss: for each student, −ln of the probability the model gave to what really happened.
E(w)=N1i∑−lnq(ki∣xi),q(k∣x)=σ(kw⋅x)
Information theory has a name for −lnp: the surprise of an outcome with probability p.
surprise=−lnp
p=1: 0, no surprise · p=0.5: 0.69 · p=0.01: 4.6, very surprised
So training = making the model as little surprised as possible by the true labels. The rest of the name comes on the next slides.
Cross-entropy: surprise when you believe the wrong thing
In general the truth is a distribution p over the classes, but you bet with the model's belief q. Your average surprise:
H(p,q)=−k∑truthp(k)lnbeliefq(k)
↓ one training example: we know its label, so the "truth" puts all its probability on ktrue (one-hot): only one term survives
H(p,q)=−lnq(ktrue∣x)=the loss of that example
Minimising cross-entropy = maximising the likelihood of the true labels. Same thing, two names.
The usual case: two classes, hard labels
Two classes: the truth is p=(t,1−t), the model says q=(σ(a),1−σ(a)).
↓ write out the sum over the two classes
H(p,q)=−tlnσ(a)−(1−t)ln(1−σ(a))
the "binary cross-entropy" of every library
A hard label is one-hot: t=1 (pass) or t=0 (fail). One term vanishes. And H(p)=0: a one-hot p holds no surprise, so nothing is "cross" yet.
The assignment writes k∈{−1,+1} and ln(1+e−ka). Same?
↓ k=+1 (t=1): only the first term
−lnσ(a)=ln(1+e−a)
↓ k=−1 (t=0): only the second; 1−σ(a)=σ(−a)
−lnσ(−a)=ln(1+ea)
↓ both are ln(1+e−ka)
Same loss, the labels are just written differently.
Every label is hard. Where does a soft p come from?
Ten students all studied 3 h: 7 passed, 3 failed. Each label is hard. What should the model say at x=3?
↓ add up their losses: 7 × −lnq and 3 × −ln(1−q); divide by 10
−0.7lnq−0.3ln(1−q)=H(p^,q),p^=(0.7,0.3)
The best q is the honest one, q=p^: 0.61. The overconfident 0.9 is worse than knowing nothing (0.5).
↓ at q=p^ the cross-entropy is the entropy of p^: its own average surprise
H(p^)=−k∑p^(k)lnp^(k)=0.61
A floor: same x, different outcomes. No model can do better.
KL=H(p^,q)−H(p^): the part a better model can remove.
Which weather forecaster is better?
10 days, it rained on 8. Three forecasters say the same number every day:
says "rain" with
accuracy (cut at 0.5)
cross-entropy −0.8lnq−0.2ln(1−q)
Alice
99 %
80 %
0.93
Bob
80 %
80 %
0.50
Cecil
50 %
undecided
0.69
Accuracy cannot tell Alice and Bob apart. Cross-entropy can: it rewards honest probabilities and punishes overconfidence hard.
That is why we train with cross-entropy and not with accuracy (also: accuracy has zero gradient almost everywhere).
Quick check
Your training loss stops at 0.45 and will not go lower, whatever you try. Is it a bug?
If the same x comes with different labels, the best possible loss is the entropy of the labels there, not 0. (A too large step makes the loss go up or jump around, not stall.)
A model always says 99 % for the class it picks, and is right 80 % of the time. Compared with a model saying 80 %, its cross-entropy is…
H(p,q)=−∑kp(k)lnq(k): −0.8ln0.99−0.2ln0.01=0.93 vs. 0.50 for the honest 80 %.
Part 5
Regularisation is a prior
What if the classes do not overlap?
New class: nobody under 3 h passed, nobody over 3 h failed. What does ML do?
w1=1: everyone on the right side, but unsure.
w1=3: surer, E drops from 0.24 to 0.05.
Steeper is always a bit better: E→0 only as w1→∞. ML wants infinite weights: a step function, 100 % sure.
It would bet everything that a 3.1 h student passes. Remember: 3 heads of 3 → θ^ML=1.
We want to say: "weights are probably not huge". That is a prior → MAP.
MAP: the data plus what we believed before
Last week, MAP: maximise the posterior instead of the likelihood.
w^MAP=argwmaxp(w∣D)
↓ Bayes' rule; p(D) does not depend on w, drop it
=argwmaxp(D∣w)p(w)
↓ −ln: the product becomes a sum, max becomes min
=argwmin[data loss−lnp(D∣w)penalty−lnp(w)]
Like a tug of war
Likelihood: "fit the data".
Prior: "stay believable".
MAP: the compromise. The coin: 7 heads of 8 with prior Beta(5, 5) gave θ^MAP=1611=0.69 instead of 0.88.
Which prior for the weights?
"Weights are probably small." As a distribution for each weight w?
↓ a Gaussian centred at 0: most of its mass near 0 (∣w∣<2s with 95 %)
p(w)∝exp(−2s2w2)
↓ take −ln: a parabola, 0 at w=0, growing with ∣w∣: a penalty for large weights
−lnp(w)=2s2w2+const
↓ independent weights: the product of priors becomes a sum of penalties
Data loss −lnp(D∣w)=NE(w) (the sum, not the mean). Add the penalty:
w^MAP=argwmin[NE(w)+2s2∥w∥2]
↓ divide by N: the minimum stays where it is
=argwmin[E(w)+λ∥w∥2],λ=2s2N1
L2 regularisation (weight decay in neural networks) = MAP with a Gaussian prior.
"L2 = weight decay" holds for plain gradient descent; with Adam the two differ, hence AdamW.
How to read it
Narrow prior (small s): large λ, small weights.
More data (large N): small λ: the data outvote the prior, as with the coin.
In practice the bias w0 is usually not penalised: shifting the boundary is not "overconfidence".
L2 or L1?
A Laplace prior p(w)∝e−∣w∣/b gives the penalty λ∑j∣wj∣: L1 (lasso).
Picture: the smallest data loss (orange ellipses around ML) that still has a small penalty (blue region).
The L1 diamond has corners on the axes: the solution often lands there, so some weights are exactly 0: feature selection.
L2 shrinks all weights a little, rarely to 0; smooth, easy to optimise.
What it looks like on MNIST
no regularisationL2: small and smoothL1: a few pixels, the rest 0
The 784 weights of a digit classifier drawn as a 28×28 image (red positive, blue negative, white 0). Mind the different colour scales.
Slide credit: Jonas
Try it: the strength of the prior λ
Quick check
λ→∞ (bias not penalised). What does the model predict?
The penalty forces w1→0, so p=σ(w0) for everyone: the share of passing students. An infinitely narrow prior: the data are ignored.
We collect 10× more students, same prior. The effect of the prior…
λ=2s2N1: 10× more data, 10× smaller λ. The data outvote the prior; MAP → ML.
How do we choose λ?
Or the features, or the model: how do we know we chose right?
Not on the training data: the training loss is always lowest at λ=0 (like h→0 for Parzen windows).
Validation: hold out part of the data, train with each λ, keep the one with the lowest validation error.
The test set is touched once, at the very end, to report the result.
Part 6
Logistic regression in the big picture
Must we cut at p=0.5?
The school offers extra tutoring. Tutoring a student who would pass anyway costs 1; missing one who fails costs 4. When do we decide d= "tutor"?
↓ Bayes lab: risk of a decision = expected loss under the posterior p=p(+1∣x)
R(tutor)=1⋅p,R(skip)=4(1−p)
↓ tutor when its risk is smaller; collect p on the left
p<4−4p⟺5p<4⟺p<0.8
Logistic regression gives probabilities, so a new loss only moves the cut. No retraining. The perceptron and SVM (next labs) give only a side of the line.
Generative or discriminative?
Discriminative (logistic regression): learns p(k∣x) directly. Only "how to label", not how x is produced.
Generative (MLE lab + Bayes): learns p(x∣k)p(k). Can also generate new samples, and gives p(k∣x) via Bayes. Not the other way round.
How many numbers do we need to learn?
Generative: a Gaussian per class
In D dimensions: mean D + covariance (symmetric) D(D+1)/2, two classes, one prior:
2(D+D(D+1)/2)+1=O(D2)
MNIST, D=784: 617 009
Logistic regression
one weight per feature + bias:
D+1=O(D)
MNIST: 785
Fewer parameters: less data needed to estimate them well.
D too big: slow to evaluate and learn → GPUs, feature selection (AdaBoost later). N too big: use a random minibatch per step → stochastic gradient descent.
Can we read the weights?
Every weight says how much its feature moves the log-odds.
Students: w1=1.79 per hour. One more hour multiplies the odds of passing by e1.79≈6.
∣wj∣ large → feature j matters. Only if the features have the same scale (hours vs minutes!): standardise first.
← more interpretableless interpretable →
decision trees
linear regression
logistic regression
random forest
neural network
CNN
More than two classes?
One score per class, ak=wk⋅x. How to turn K scores into probabilities?
↓ ea makes them positive, dividing by the sum makes them add up to 1
p(k∣x)=∑j=1Keajeak(softmax)
↓ K=2: divide top and bottom by ea1
p(1∣x)=ea1+ea2ea1=1+e−(a1−a2)1=σ(a1−a2)
The sigmoid is softmax with two classes; only the difference of scores matters.
Example: 5 classes
scores (1.3,5.1,2.2,0.7,1.1)
probabilities (0.02,0.90,0.05,0.01,0.02)
The largest score wins, but every class keeps some probability. Loss: −ln of the true class's probability, as before.
Logistic regression is one neuron
Weighted sum, then a sigmoid: the classic artificial neuron.
Add a hidden layer: the network learns its own featuresh, then does logistic regression on them. Same loss (cross-entropy), same training (gradient descent), L2 = weight decay (with Adam: AdamW).
Only straight boundaries?
Feature lifting: transform x with fixed functions (here x↦(x,x2)), then the boundary is straight in the new space and curved in the old one. Bonus task: arctan features.
Which functions? Try a set, validate, intuition… Learning them instead: that is deep learning.
Part 7
The assignment
The assignment in one slide
Part 1: letters A vs C
One feature (left half minus right half of the image, standardised), labels k∈{−1,+1}.
Loss (given): E(w)=N1∑ln(1+e−kw⋅x)
You: its gradient, gradient descent with the adaptive step, the 1D threshold, classification.
Part 2: MNIST digits
784 pixels + bias, the same code. Look at the learned weights as an image.
Bonus
Feature lifting: a curved boundary (Prince, ch. 9). Keep k∈{−1,+1}.
Logistic regression in five lines
Assume the log-odds is linear: p(k∣x)=σ(kw⋅x). Boundary: a hyperplane.
ML for the labels = minimise the cross-entropy E(w) ("surprise" at the true labels).
No closed form, but convex: gradient descent.
MAP with a Gaussian prior = L2 regularisation: it stops infinite weights. Pick λ by validation.
Softmax for K classes; stack neurons and you have a neural network.
Next
Next week: exercises
Then: test 2 (13. 11.)
Feedback, please!
Optional
More on cross-entropy, and logistic regression today
Cross-entropy, entropy and KL divergence
How much extra surprise do we pay for believing q instead of the truth p?
DKL(p∥q)=k∑p(k)lnq(k)p(k)
↓ lnqp=lnp−lnq, split the sum
=k∑p(k)lnp(k)−k∑p(k)lnq(k)
↓ recognise both sums
=−H(p)+H(p,q)≥0
H(p) does not depend on the model, so minimising H(p,q) = minimising DKL.
Why train with CE and not KL? Same minimum, and with one-hot labels H(p)=0 anyway; CE is simpler and its value does not shift with the label mix of each minibatch.
Soft labels on purpose
Same formula H(p,q)=−∑kp(k)lnq(k), but now each example's target p is soft on purpose:
Label smoothing (Inception v3, ViTs): target (1−ε,ε) instead of (1,0).
Knowledge distillation: a small "student" network learns from the teacher's probabilities qteacher ("this 7 looks a bit like a 1").
Annotator disagreement / multi-label: 3 of 5 annotators say "cat", 2 say "dog" → p=(0.6,0.4).
Why smoothing helps
Target (0.95,0.05): the best q is 0.95, not 1.
So the weights stay finite: the same cure as the prior on separable data, from the other side.
No regularisation, separable classes: ∥w∥→∞. But in which direction?
Gradient descent on the logistic loss converges in direction to the maximum-margin line: the one as far as possible from the nearest points of both classes.
That line is exactly what a (hard-margin) SVM finds on purpose: lab 9.
Slowly (like 1/lnt), but it explains part of why huge, unregularised networks still generalise: the optimiser itself prefers "simple", large-margin solutions (implicit bias).
Logistic regression inside a vision–language model
SigLIP (behind many current VLMs): one batch of B images and their captions. Every image–text pair (i,j) is one training example of logistic regression:
aij=txi⋅yj+b,kij={+1−1i=ji=j
↓ the assignment's loss, summed over all B2 pairs
L=B1i,j∑ln(1+e−kijaij)
Only B of the B2 pairs match, so the bias starts at b=−10: the prior log-odds of "this pair matches" are very negative. CLIP uses softmax over each row instead.
CLIP, DINOv2, … are trained without our labels. How good are their features for a new task?
Linear probe: freeze the network, take its features h(x), and train logistic regression on top. Better features → higher probe accuracy.
CLIP's paper: scikit-learn's logistic regression, with the L2 strength λ chosen on a validation set. Exactly today's lab, on 768-dim features instead of 1 or 784.
It is the "feature lifting" slide with the lifting learned on millions of images.
Radford et al., CLIP, 2021 (appendix A); Oquab et al., DINOv2, 2023
Language models: the same loss, 100 000 classes
An LLM reads "The cat sat on the" and must predict the next token. How is it trained?
One score per token of the vocabulary (~100k classes), softmax, loss −lnq(true next token): multinomial logistic regression on top of a huge network.
↓ the reported number is the exponential of the average cross-entropy
perplexity=eCE
CE =2.3 → perplexity e2.3≈10: as unsure as picking uniformly from 10 tokens
"Which answer is better?" Training from preferences
People compare two chatbot answers A and B and pick the better one. How do we learn a score r from that?
↓ Bradley–Terry (1952): the probability of preferring A depends on the score difference
p(A≻B)=σ(r(A)−r(B))
↓ maximum likelihood of the human choices, as today
L=−lnσ(r(chosen)−r(rejected))=ln(1+e−m)
Our logistic loss with margin m=r(chosen)−r(rejected). Reward models for RLHF use exactly this; DPO puts the same −lnσ(⋅) directly on the language model.
The "cut at 0.8" slide needs honest probabilities: of all students with p=0.8, about 80 % should pass. Is that true?
Logistic regression: usually close (it is trained with a proper scoring rule, like Bob the forecaster). Modern deep networks: often overconfident, like Alice.
↓ temperature scaling: divide all scores by one number T, fitted by minimising cross-entropy on a validation set
q(k∣x)=softmax(a/T)k,T>1 softens
One-parameter logistic regression on top of a network. For an SVM's scores s: Platt scaling, σ(αs+β): logistic regression again.
An object detector scores ~100 000 boxes per image; almost all are background and easy. Cross-entropy sums them all: thousands of tiny losses can drown the few hard ones.
↓ multiply the loss by (1−qt)γ, small when the model is already right (qt = probability of the true class)
FL=−(1−qt)γlnqt,γ=2
easy, qt=0.9: CE 0.105 → FL 0.001 (100× less)
hard, qt=0.1: CE 2.30 → FL 1.87 (almost unchanged)