Lecture 3

Classification and logistic regression

Introduction to Machine Learning
KU Leuven, campuses Diepenbeek and Geel
Academic year 2026–2027

Where we left off

As \(\lambda\) grows without bound, ridge predicts the mean of the training targets.

Now take the bearings of lecture 1, one in ten of them faulty, and code healthy \(= 0\) and faulty \(= 1\).

Then that mean is 0.1, for every bearing.

Today

Is 0.1 a probability? And is a regression model the right tool when the target is a class?

Today in three choices

Model

\(p = \sigma(\vw\T\vx)\)

a linear score, squashed into a probability

Loss

cross-entropy

confident mistakes cost the most

Optimiser

gradient descent

the closed form is gone for good

The plan

  1. Classification, and why least squares fails at it
  2. Logistic regression
  3. Evaluating a classifier

Exercise 2, after lecture 4, builds this model in numpy and evaluates it.

Block 1

Classification

Healthy or faulty

A thousand rolling bearings for training, two measurements each:

  • vibration RMS, in mm/s
  • bearing temperature, in °C

One bearing in ten is faulty.

A scatter plot of temperature against vibration: healthy bearings cluster at low vibration, faulty ones spread towards high vibration and high temperature, and the two groups overlap.

Labels as numbers

Two classes

healthy \(\to 0\), faulty \(\to 1\)

The numbers are names. Their order and their distance carry no meaning.

More classes

healthyfaultyworn
healthy100
worn001

One-hot coding, as for the categorical features of lecture 1.

A classifier is a decision rule

  • It assigns a class to every point of the feature space
  • So it divides the space into regions, one per class
  • The decision boundary is where the regions meet

Learning a classifier means placing the boundary.

A linear boundary

Score: \(z = \vw\T\vx\)

  • \(z > 0\): faulty, \(z < 0\): healthy
  • The boundary is the line \(z = 0\)
  • \(|z|\) grows with the distance from the line
The bearing scatter plot divided by a straight line into a predicted healthy region at low vibration and a predicted faulty region beyond it.

Least squares on the labels

Two panels of labels against vibration with a fitted straight line. Left, bearings up to 8 mm/s, with the line crossing 0.5 at 3.9 mm/s. Right, all bearings, with the line flatter and crossing 0.5 at 4.9 mm/s.
Fit a line to the zeros and ones, and call a bearing faulty where the line exceeds 0.5.

Where it breaks

  • The line predicts below 0 and above 1
  • Eight bearings above 8 mm/s pull the line flatter
  • The threshold moves from 3.9 to 4.9 mm/s
  • Faulty bearings in between are now called healthy

The most obvious faults made the classifier worse. Least squares punishes them for being far from 1, even though they are on the correct side.

What is needed instead

  1. An output between 0 and 1, which reads as a probability
  2. A loss that ignores points far on the correct side
  3. A loss that punishes confident mistakes hard

Block 2 builds all three.

Checkpoint

The least-squares model predicts 1.4 for a bearing. What does that number mean?

Block 2

Logistic regression

Squash the score

\[ \sigma(z) = \frac{1}{1 + e^{-z}} \]
  • Any score maps into \((0, 1)\)
  • \(\sigma(0) = 0.5\)
  • Large scores saturate, so points far on the correct side stop mattering
The sigmoid function: an S-shaped curve rising from 0 to 1, passing 0.5 at a score of zero.

From score to class

\[ p = \sigma(\vw\T\vx) = P(y = 1 \mid \vx) \]

\(p \ge 0.5\) exactly when \(z \ge 0\).

So the boundary is still the line of block 1. The sigmoid adds a probability, and moves nothing.

A chain of six boxes: features, score, sigmoid, probability, threshold and class, with the values of one bearing at 3.5 mm/s and 62 °C: a score of 1.41, a probability of 0.80, and the class faulty.

The model on the bearings

The feature space shaded from blue to red by the predicted probability of a fault, with the 0.5 contour drawn as a straight line and the bearings overlaid.
The probability changes across a band around the boundary, and is close to 0 or 1 everywhere else.

Reading the weights

\[ z = \log \frac{p}{1 - p} \]

The score is the logarithm of the odds of a fault.

On standardised features: vibration \(2.85\), temperature \(1.42\).

One standard deviation more vibration multiplies the odds of a fault by \(e^{2.85} \approx 17\), and one more of temperature by about 4. Both raise the risk, and vibration raises it more.

A loss for probabilities

Cost of one prediction: \(-\log\) of the probability given to the true class.

  • Right and confident: close to 0
  • Unsure: about 0.7
  • Wrong and confident: without bound
Two curves of cost against the predicted probability of a fault: minus log p falls to zero at p equal to one, while minus log of one minus p rises without bound as p approaches one.

Binary cross-entropy

\[ \loss(\vw) = -\frac{1}{n} \sum_{i=1}^{n} \Big[ y^{(i)} \log p^{(i)} + \big(1 - y^{(i)}\big) \log \big(1 - p^{(i)}\big) \Big] \]

For a faulty bearing only the first term remains: \(-\log p^{(i)}\).

For a healthy bearing only the second remains: \(-\log \big(1 - p^{(i)}\big)\).

The loss is the average cost of the previous slide.

It is a likelihood

Read \(p^{(i)}\) as the probability of a coin that lands on faulty.

The cross-entropy is the negative log-likelihood of the observed labels under those coins.

Minimising it picks the weights under which the observed labels are most probable. The same principle, applied to measurements with Gaussian noise, gives least squares.

The derivative of the sigmoid

\[ \sigma(z) = \left(1 + e^{-z}\right)^{-1} \]
\[ \sigma'(z) = \frac{e^{-z}}{\left(1 + e^{-z}\right)^2} = \frac{1}{1 + e^{-z}} \cdot \frac{e^{-z}}{1 + e^{-z}} \]
\[ \sigma'(z) = \sigma(z)\,\big(1 - \sigma(z)\big) \]

The derivative is built from the output itself, which the forward pass has already computed.

The gradient, by the chain rule

\[ \ell = -y \log p - (1 - y) \log(1 - p), \quad p = \sigma(z), \quad z = \vw\T\vx \]
\[ \frac{\partial \ell}{\partial \vw} = \frac{\partial \ell}{\partial p} \cdot \frac{\partial p}{\partial z} \cdot \frac{\partial z}{\partial \vw} = \left( \frac{p - y}{p(1 - p)} \right) \cdot p(1 - p) \cdot \vx = (p - y)\,\vx \]
\[ \nabla \loss(\vw) = \frac{1}{n} \mX\T (\vp - \vy) \qquad \text{lecture 1:} \quad \frac{2}{n} \mX\T (\mX\vw - \vy) \]

Prediction minus target, weighted by the features: the same form as least squares.

Gradient descent for logistic regression

Pseudocode

input: X, y, learning rate η, steps T
w ← 0
repeat T times:
    p ← σ(X w)
    g ← (1/n) Xᵀ (p − y)
    w ← w − η g
return w

numpy

n = len(y)
w = np.zeros(X.shape[1])
for step in range(T):
    p = 1 / (1 + np.exp(-X @ w))
    g = X.T @ (p - y) / n
    w = w - eta * g

No closed form, but one minimum

Setting the gradient to zero gives no formula for \(\vw\).

The cross-entropy is convex in \(\vw\), so gradient descent still reaches the global minimum.

The mean cross-entropy against the gradient descent iteration on a logarithmic axis, falling from 0.69 and levelling off at the minimum found by scikit-learn.

More than two classes: softmax

One score per class, \(z_k = \vw_k\T\vx\):

\[ p_k = \frac{e^{z_k}}{\sum_{j=1}^{K} e^{z_j}} \]

The probabilities are positive and sum to 1. The loss is \(-\log\) of the probability of the true class. With two classes, softmax is the sigmoid.

The bearing feature space with worn bearings added, divided into three regions: healthy at low vibration, worn in a band beyond it, and faulty at high vibration.

The bridge to scikit-learn

LogisticRegression(C=...) minimises

\[ C \sum_{i=1}^{n} \ell^{(i)} + \tfrac{1}{2} \lVert \vw_{1:p} \rVert^2 \]

a penalty by default, with \(C = 1\). In the notation of lecture 2, \(\lambda = \frac{1}{2nC}\).

These slides use no penalty:

LogisticRegression(C=np.inf)

With the default, the first weight here is 2.62 instead of 2.85. Neither is a bug.

Checkpoint

On perfectly separable data, without a penalty, what happens to the weights?

Break

Ten minutes

Block 3

Evaluating a classifier

94.7% accuracy

The model of block 2, on a thousand test bearings.

A model that always answers "healthy" scores 90.0%.

With one fault in ten, accuracy is dominated by the healthy bearings, and says little about the faults that matter.

The confusion matrix

A two by two table of the test bearings: 882 true negatives, 18 false positives, 35 false negatives and 65 true positives.
  • Positive: the class being searched for, here faulty
  • False positive: a false alarm
  • False negative: a missed fault

35 of the 100 faulty bearings were missed.

Precision and recall

\[ \text{precision} = \frac{TP}{TP + FP} = \frac{65}{83} = 0.78 \]

Of the bearings flagged as faulty, the share that is faulty.

\[ \text{recall} = \frac{TP}{TP + FN} = \frac{65}{100} = 0.65 \]

Of the faulty bearings, the share that was flagged.

Which mistake costs more

A missed fault

The bearing seizes, and the gearbox or the line stops.

Recall protects against this.

A false alarm

A technician inspects a healthy bearing.

Precision protects against this.

One number: F1

\[ F_1 = \frac{2 \cdot \text{precision} \cdot \text{recall}}{\text{precision} + \text{recall}} = 0.71 \]

The harmonic mean is low when either score is low, so a detector cannot hide a poor recall behind a good precision.

Useful for comparing models when the two mistakes cost about the same. When they do not, report both scores.

The threshold is a choice

Nothing forces the threshold to be 0.5.

  • At 0.5: precision 0.78, recall 0.65
  • At 0.2: precision 0.53, recall 0.76

A lower threshold catches more faults and raises more false alarms.

Precision rising and recall falling as the threshold moves from 0 to 1, with a dotted line at 0.5.

Every threshold at once: the ROC curve

The ROC curve of the logistic model, rising steeply towards the top left corner, above the diagonal of chance, with the always healthy model marked at the origin.
Each point is one threshold: the share of healthy bearings flagged against the share of faults caught. The constant healthy model sits in the corner at zero.

The area under the curve

AUC \(= 0.90\)

Pick a random faulty and a random healthy bearing. The AUC is the probability that the model gives the faulty one the higher score.

1 is perfect, 0.5 is chance. The AUC does not depend on the threshold, so it compares models before the threshold is chosen.

Remedy 1: weight the classes

\[ \loss(\vw) = -\frac{1}{n} \sum_{i=1}^{n} \Big[ a_1\, y^{(i)} \log p^{(i)} + a_0 \big(1 - y^{(i)}\big) \log \big(1 - p^{(i)}\big) \Big] \]

class_weight="balanced" sets \(a_1 = 5\) and \(a_0 = 0.56\), so both classes carry equal total weight.

Here recall rises from 0.65 to 0.79, while precision falls from 0.78 to 0.36.

Remedy 2: move the threshold, honestly

  • Choose the threshold on validation data, never on test data
  • Resample, i.e. duplicate faults or drop healthy bearings, only inside the training folds

The leakage rule of lecture 2 applies unchanged. A resampled validation fold no longer resembles the bearings met in service.

The recipe, for a classifier

  1. Split with stratification, so that both parts keep one fault in ten
  2. Build a pipeline: standardise, then classify
  3. Cross-validate on stratified folds, scoring recall, F1 or AUC rather than accuracy
  4. Choose the threshold on validation data
  5. Measure on the test data, once

The five steps of lecture 2, with two changes: stratify the splits, and choose the score to suit the costs.

Checkpoint

A detector has a recall of 99% and a precision of 5%. Is it useful?

Takeaways

  1. A classifier is a boundary, and a linear score gives a straight one.
  2. The sigmoid turns the score into a probability without moving the boundary.
  3. Cross-entropy punishes confident mistakes, and its gradient has the form of lecture 1.
  4. Accuracy hides imbalance. Report precision and recall, or the ROC curve.
  5. The threshold is a design decision that follows from the cost of each mistake.

Lecture 3 in three choices

Model

\(p = \sigma(\vw\T\vx)\), softmax

a linear score, read as a probability

Loss

cross-entropy

the negative log-likelihood of the labels

Optimiser

gradient descent

the change from lecture 2: no closed form

Further reading

All three books are free to read online.

Next

Lecture 4

Decision trees and ensembles: a model that splits the feature space into boxes, and the frame breaks.

Exercise 2, after lecture 4

Grid stability: logistic regression in numpy, its evaluation, then trees and forests.

It uses today's lecture for its first half.