06 - Logistic Regression

Pattern Recognition and Machine Learning, Lab 6

Michal Neoral

neoramic@fel.cvut.cz

30 October 2026

Recap

Where are we?

Lab 2: Bayes

  • \(\cp(\cx \mid \ck)\), \(\cp(\ck)\) known
  • optimal strategy \(\cq^*(\cx)\)

We know everything.

Labs 4 and 5: estimate

  • \(\cp(\cx \mid \ck)\) unknown
  • estimate it: Parzen, ML, MAP, Bayes
  • then plug into Bayes

Generative: a model of how \(\cx\) looks.

Today

  • we need only \(\cp(\ck \mid \cx)\)
  • estimate it directly

Discriminative: a model of the decision.

today

To decide, we do not need to know how the data look. We need \(\cp(\ck \mid \cx)\), nothing more.

Two ways to the posterior

Generative model: two normal densities as ellipses around the two classes

Next to it the discriminative model: only the decision line and the posterior

Generative: model \(\cp(\cx \mid \ck)\, \cp(\ck)\), get \(\cp(\ck \mid \cx)\) by Bayes. Can generate new data.

Discriminative: model only \(\cp(\ck \mid \cx)\). Simpler, but no model of the data.

From Bayes to log odds

Bayesian strategy, 0/1 loss, two classes

\[ \cq^*(\cx) = \arg\max_{\ck} \cp(\ck \mid \cx) \]

\[ \cq^*(\cx) = \cone \quad\text{if}\quad \cp(\cone \mid \cx) > \cp(\ctwo \mid \cx) \;\Leftrightarrow\; \frac{\cp(\cone \mid \cx)}{\cp(\ctwo \mid \cx)} > 1 \;\Leftrightarrow\; \underbrace{\ln \frac{\cp(\cone \mid \cx)}{\cp(\ctwo \mid \cx)}}_{\ca(\cx)\ \text{log odds}} > 0 \]

Have you seen this ratio before?

Not the likelihood ratio \(\frac{\cp(\cx \mid \cone)}{\cp(\cx \mid \ctwo)}\) from minimax. This is the ratio of the posteriors, the odds.

The simplest choice: a linear log odds

Model the log odds directly, as a linear function of \(\cx\):

\[ \ca(\cx) = \ln \frac{\cp(\cone \mid \cx)}{\cp(\ctwo \mid \cx)} = w_0 + \mathbf{w}_1^\top \cx = \cw^\top \cbx \]

The bias is hidden in the vector: \(\cbx = [1, \cx]\), \(\cw = [w_0, \mathbf{w}_1]\).

For many problems the log odds is linear: e.g. two normal classes with the same covariance (later).

  1. Express \(\cp(\cone \mid \cx)\) and \(\cp(\ctwo \mid \cx)\) using \(\ca(\cx) = \cw^\top \cbx\).
  2. Show that \(1 - \csig(u) = \csig(-u)\) for \(\csig(u) = \frac{1}{1 + e^{-u}}\).

More problems like this: exercise book on CourseWare.

The logistic sigmoid

The logistic sigmoid from 0 to 1, value one half at zero, symmetric around this point

\(\cp(\cone \mid \cx) = \csig(\cw^\top \cbx)\)
\(\cp(\ctwo \mid \cx) = \csig(-\cw^\top \cbx)\)

  • a probability in \((0, 1)\)
  • \(\csig(0) = \frac{1}{2}\): the boundary
  • \(\csig(-u) = 1 - \csig(u)\)
  • \(\csig' = \csig\,(1 - \csig)\)

Does it look familiar?

\(\tanh u = 2\, \csig(2u) - 1\), a normal CDF (Lab 2)

What \(w_0\) and \(w_1\) do (1D)

Sigmoids with slopes 0.5, 1.5 and 5, all crossing one half at zero

Adds sigmoids shifted by the bias minus two, zero and two

Adds a sigmoid with a negative slope, the classes swap sides

\(\cp(\kp \mid x) = \csig(w_0 + w_1 x)\): larger \(|w_1|\), steeper, more confident.

\(w_0\) shifts the curve: \(\cp = \frac{1}{2}\) at \(x = -w_0 / w_1\).

The sign of \(w_1\): which class is on which side.

Logistic regression: try it

The threshold in 1D

\[ \cp(\kp \mid x) = \csig(w_0 + w_1 x) \]

Labels \(\ck \in \{\kp, \km\}\) from now on, as in the assignment.

  1. For which \(x\) is \(\cp(\kp \mid x) = \cp(\km \mid x) = \frac{1}{2}\)?
  2. \(\cw = (1.5, -0.7)\): the threshold? Which side is \(\kp\)?
  3. Write the strategy \(\cq(x)\).

More problems like this: exercise book on CourseWare.

Derivation: the threshold in 1D

\[ \csig(w_0 + w_1 x) = \tfrac{1}{2} \;\Leftrightarrow\; w_0 + w_1 x = 0 \;\Leftrightarrow\; \boxed{x^* = -\frac{w_0}{w_1}} \]

\[ \cw = (1.5, -0.7): \qquad x^* = -\frac{1.5}{-0.7} \approx 2.14, \qquad w_1 < 0 \;\Rightarrow\; \cp(\kp \mid x) \text{ decreases} \]

\[ \cq(x) = \begin{cases} \kp & \text{if } x < 2.14 \\ \km & \text{if } x \geq 2.14 \end{cases} \]

More dimensions: a linear decision boundary

Two classes of points in the plane, blue upper right, red lower left

Contours of the posterior probability, parallel straight lines

The decision line where the posterior is one half and the weight vector perpendicular to it

The same points in 3D: blue at height one, red at height zero

The posterior as a surface over the plane: a sigmoid step along one direction, constant along the other

The surface cut by a horizontal plane at one half, the cut is a straight line

\(\cx \in \mathbb{R}^2\), \(\cp(\kp \mid \cx) = \csig(w_0 + w_1 x_1 + w_2 x_2)\): a surface over the plane.

A sigmoid along \(\cw\), constant across it: the contours are parallel lines.

Boundary \(\cw^\top \cbx = 0\): the surface cut at \(\frac{1}{2}\), a line (\(\mathbb{R}^D\): a hyperplane) \(\perp \cw\).

Logistic regression is a linear classifier: it can only cut the space by a hyperplane.

Learning \(\cw\)

Labels \(\pm 1\): one formula for both classes

\[ \begin{aligned} \cp(\kp \mid \cx) &= \csig(\cw^\top \cbx) \\ \cp(\km \mid \cx) &= \csig(-\cw^\top \cbx) \end{aligned} \]

\[ \Downarrow \] \[ \boxed{\cp(\ck \mid \cx) = \csig(\ck\, \cw^\top \cbx)} \]

Training set: \[ \cT = \{(\cx_1, \ck_1), \dots, (\cx_N, \ck_N)\} \] \[ \ck_i \in \{\kp, \km\} \]

How to find \(\cw\)? We have seen it last week.

Maximum likelihood for \(\cw\)

\[ \ell(\cw) = \sum_{i=1}^{N} \ln \cp(\cx_i, \ck_i \mid \cw) = \sum_{i=1}^{N} \ln \cp(\ck_i \mid \cx_i, \cw) + \underbrace{\sum_{i=1}^{N} \ln \cp(\cx_i)}_{\text{does not depend on } \cw} \]

\[ \cw^* = \arg\max_{\cw} \sum_{i=1}^{N} \ln \csig(\ck_i\, \cw^\top \cbx_i) = \arg\min_{\cw} \underbrace{\frac{1}{N} \sum_{i=1}^{N} \ln\big(1 + e^{-\ck_i\, \cw^\top \cbx_i}\big)}_{E(\cw)} \]

Result: \(E(\cw)\) is convex: one minimum, but no closed form. We need a numerical method.

Cross-entropy loss

Loss of one sample as a function of the signed margin, compared with the 0/1 loss

Loss of one sample: \(-\ln \cp(\ck_i \mid \cx_i)\)

  • right side, confident: loss \(\approx 0\)
  • on the boundary: \(\ln 2\)
  • wrong side: grows linearly

A smooth, convex replacement of the 0/1 loss. We can take its gradient.

Cross-entropy, entropy, KL divergence

True distribution \(p\), model \(q\): \[ H(p, q) = -\sum_{\ck} p(\ck) \ln q(\ck) = \underbrace{-\sum_{\ck} p(\ck) \ln p(\ck)}_{\text{entropy } H(p)} + \underbrace{\sum_{\ck} p(\ck) \ln \frac{p(\ck)}{q(\ck)}}_{D_{\mathrm{KL}}(p \,\|\, q) \,\geq\, 0} \]

One sample, true label \(\ck_i\): \(p\) is one-hot, \(H(p) = 0\) \[ H(p, q) = -\ln q(\ck_i) = \ln\big(1 + e^{-\ck_i\, \cw^\top \cbx_i}\big) \]

Minimizing cross-entropy = minimizing KL = maximizing likelihood.

The gradient of \(E(\cw)\)

\[ E(\cw) = \frac{1}{N} \sum_{i=1}^{N} \ln\big(1 + e^{-\ck_i\, \cw^\top \cbx_i}\big) \]

  1. Compute the gradient \(\nabla E(\cw)\).
  2. Which samples push the most?

More problems like this: exercise book on CourseWare.

Derivation: the gradient

\[ \nabla E(\cw) = \frac{1}{N} \sum_{i=1}^{N} \frac{e^{-\ck_i\, \cw^\top \cbx_i}}{1 + e^{-\ck_i\, \cw^\top \cbx_i}}\, (-\ck_i\, \cbx_i) = -\frac{1}{N} \sum_{i=1}^{N} \csig(-\ck_i\, \cw^\top \cbx_i)\; \ck_i\, \cbx_i \]

\[ \boxed{\nabla E(\cw) = -\frac{1}{N} \sum_{i=1}^{N} \big(1 - \cp(\ck_i \mid \cx_i)\big)\, \ck_i\, \cbx_i} \qquad \text{badly classified samples push the most} \]

\[ \text{Hessian:}\quad H(\cw) = \frac{1}{N} \sum_{i=1}^{N} \cp(\kp \mid \cx_i)\, \cp(\km \mid \cx_i)\; \cbx_i \cbx_i^\top \;\succeq\; 0 \quad\Rightarrow\quad E \text{ is convex} \]

Gradient descent: the step size

Gradient descent with a too small step, many tiny steps

Gradient descent with a good step, reaches the minimum quickly

Gradient descent with a too large step, jumps over the minimum and diverges

\(\cw \leftarrow \cw - \eta\, \nabla E(\cw)\). Step \(\eta\) too small: slow.

Just right: a few steps to the minimum.

Too large: jumps over the minimum, may diverge.

Gradient descent with an adaptive step

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: accept, larger step
        w -= step_size * g
        E, g = E_new, g_new
        step_size *= 2
    else:                # failure: smaller step
        step_size /= 2
return w
  • accept the step only if \(E\) decreases
  • success: double the step
  • failure: halve it
  • stop: \(\|\cw_\text{new} - \cw_\text{prev}\| \leq \varepsilon\)

The gradient is normalized by \(\frac{1}{N}\): the step size does not depend on the number of samples.

Gradient descent in action

Left: contours of the loss in the plane of bias and slope with the path from the start to the minimum. Right: loss and step size per iteration

The 1D data from the interactive slide, start at \(\cw = (-7, -8)\) as in the assignment.

Separable data: ML is overconfident

Separable data, sigmoids getting steeper and steeper towards a step

Twelve sigmoids drawn from the posterior over the weights, in grey

The Bayesian prediction, the average of the sigmoids, dash-dotted

Separable data: every step of gradient descent makes \(\|\cw\|\) larger, \(E \to 0\). The limit is a step.

With a prior \(\cp(\cw)\): the posterior \(\cp(\cw \mid \cT)\), models drawn from it.

Bayes averages them (as in Lab 5): uncertain between the classes.

Generative vs discriminative

When is the log odds linear?

Two normal classes, the same \(\Sigma\): \[ \ca(\cx) = \ln \frac{\cp(\cx \mid \cone)\, \cp(\cone)}{\cp(\cx \mid \ctwo)\, \cp(\ctwo)} \]

The terms \(\cx^\top \Sigma^{-1} \cx\) cancel: \[ \ca(\cx) = \underbrace{(\mu_1 - \mu_2)^\top \Sigma^{-1}}_{\mathbf{w}_1^\top} \cx + w_0 \]

Equal variances: the logistic regression matches the true posterior

Same mean, different variances: the true posterior is a bump, the logistic regression is almost flat

Equal variances: logistic regression is the exact model.

Same mean, different variances: a quadratic log odds, logistic regression fails.

Number of parameters

Two classes, \(\cx \in \mathbb{R}^D\):

  • generative: two normal densities with a shared covariance, priors
  • logistic regression: \(\cw\)
  1. How many parameters does each model have?
  2. \(D = 2\)? \(D = 784\) (MNIST, \(28 \times 28\))?

More problems like this: exercise book on CourseWare.

Derivation: number of parameters

\[ \text{generative:}\quad \underbrace{2D}_{\mu_1, \mu_2} + \underbrace{\tfrac{D(D+1)}{2}}_{\Sigma} + \underbrace{1}_{\cp(\cone)} = O(D^2) \qquad\qquad \text{logistic regression:}\quad \underbrace{D + 1}_{\cw} = O(D) \]

\(D\) generative logistic regression
2 8 3
784 309 289 785

Fewer parameters: fewer data needed. But if the generative model is right, it uses the data better.

Interpretability

\[ \ca(\cx) = w_0 + \sum_{j=1}^{D} w_j x_j \]

  • \(|w_j|\) large: feature \(x_j\) is important
  • sign of \(w_j\): towards which class
  • \(x_j\) up by 1: the odds multiplied by \(e^{w_j}\)

Compare \(|w_j|\) only for normalized features (same scale).

feature \(x_j\) \(w_j\)
body temperature 2.1
cough 1.4
vaccinated -1.8
shoe size 0.02

A made-up example: flu (\(\kp\)) or not (\(\km\)).

Beyond two classes and lines

More classes: softmax

One \(\cw_\ck\) per class: \[ \cp(\ck \mid \cx) = \frac{e^{\cw_\ck^\top \cbx}}{\sum_{m=1}^{K} e^{\cw_m^\top \cbx}} \]

Show that for \(K = 2\) it is the sigmoid.

\[ \cp(1 \mid \cx) = \csig\big((\cw_1 - \cw_2)^\top \cbx\big) \]

\(\cw_\ck^\top \cbx\) \(e^{\cw_\ck^\top \cbx}\) \(\cp(\ck \mid \cx)\)
1.3 3.7 0.02
5.1 164.0 0.90
2.2 9.0 0.05
0.7 2.0 0.01
1.1 3.0 0.02

Exponentiate, normalize to sum 1.

Only a linear boundary?

One dimensional data with the classes alternating, a single sigmoid cannot separate them

The classes alternate. What can we do with one sigmoid?

Dimensionality lifting

Seven arctan features with different shifts

The features multiplied by learned weights

Their sum, the log odds, crosses zero four times

The posterior probability separates the alternating classes

Fixed features \(\mathbf{f}(x) = (f_1(x), \dots, f_7(x)) \in \mathbb{R}^7\): lift \(x\) into 7 dimensions.

Logistic regression in \(\mathbb{R}^7\) learns the weights \(w_j\).

\(\ca(x) = \cw^\top \mathbf{f}(x)\): linear in \(\mathbf{f}\), nonlinear in \(x\).

Three thresholds in \(x\): the bonus task (after Prince, 2012).

Towards neural networks

Logistic regression drawn as one neuron: inputs, weighted sum, sigmoid, probability

A hidden layer of features before the neuron: fixed for lifting, learned in a neural network

Logistic regression: a weighted sum and a sigmoid, one neuron.

Features in a hidden layer: fixed (lifting) or learned (neural network, Lab 12).

High dimensions, many samples

Large \(D\) (e.g. \(10^9\))

  • slow evaluation
  • slow learning
  • GPUs

Large \(N\)

  • full gradient: slow
  • SGD: gradient from a random mini-batch

Few good features

  • incremental: add features one at a time
  • \(\ca(\cx) = \sum_{j=1}^{M} w_j f_j(\cx)\), \(M \ll D\)
  • AdaBoost (Lab 10)

Regularization

\[ E_\lambda(\cw) = E(\cw) + \lambda \|\cw\|_2^2 \]

  • L2 (ridge): MAP, a normal prior on \(\cw\) (Lab 5)
  • L1 (lasso), \(\lambda \|\cw\|_1\): a sparse \(\cw\)
  • weight decay in neural nets

Separable data: \(\|\cw\|\) stays finite.

L1 constraint as a diamond touching the loss contours at a corner, L2 constraint as a circle touching them elsewhere

Regularization on MNIST: the weights

no regularization Weight image without regularization: noisy pixels everywhere

L2 Weight image with L2 regularization: smooth, shows the shape of digits

L1 Weight image with L1 regularization: only a few pixels are nonzero

How to choose \(\lambda\), the features, the model? Validation (cross-validation from Lab 4).

One weight per pixel (784), from a solution of the assignment in previous years.

The assignment

Assignment: logistic regression

Part 1: letters A and C

  • 1D feature: left minus right
  • loss, gradient, descent
  • test error about 7 %

Part 2: MNIST

  • pixels: \(D = 784\)
  • the same functions
  • the weights as an image

Bonus: lifting

  • \(\arctan\) features (Prince)
  • nonlinear boundary in 1D
  • labels \(\pm 1\), not 0, 1

Add the 1 for the bias, normalize the test data with the training mean and variance, and divide the gradient by \(N\).

Take-away for the lab

  • Discriminative: model \(\cp(\ck \mid \cx)\) directly, no \(\cp(\cx \mid \ck)\)
  • Linear log odds \(\iff\) \(\cp(\ck \mid \cx) = \csig(\ck\, \cw^\top \cbx)\), a linear boundary
  • ML \(=\) min of the cross-entropy: convex, solved by gradient descent
  • Separable data: \(\|\cw\| \to \infty\), use a prior (regularization) or Bayes
  • Softmax for more classes, lifting for nonlinear boundaries: towards neural networks