COMP328 Fundamentals of Machine Learning

Module 2 · Unit 5

Supervised Learning Logistic Regression

Move from predicting how much to predicting which one. This unit shows how a linear model becomes a classifier: squash the score through a sigmoid, read the output as a probability, and choose a threshold that reflects the real cost of being wrong.

8 tutorials ≈4 hours guided study 1 quiz 1 assignment

01 Why this unit

Most of the decisions machine learning is asked to support are binary. Will this customer leave? Is this transaction fraudulent? Should this loan be approved? Logistic regression is the workhorse model for exactly these questions — and it remains one of the most widely deployed classifiers in industry.

The unit is also where a subtle but important shift happens. In Unit 4 the model output was the prediction. Here the model output is a score, which is then converted into a probability, which is then converted into a decision by comparing it against a threshold. Three distinct steps, and each one can be evaluated and tuned separately. Understanding that separation is the main conceptual payoff of the unit.

What makes this unit different

  • The output is bounded. A probability must lie between 0 and 1, which is exactly what the sigmoid enforces.
  • The loss is not squared error. Logistic regression is fitted by maximum likelihood, which produces the cross-entropy loss.
  • The threshold is a choice, not a fact. 0.5 is a default, not a law — and often the wrong default.
  • Interpretability survives. Coefficients become odds ratios, which stakeholders can reason about directly.
The logistic sigmoid function plotted as an S-shaped curve A plot of the sigmoid function mapping a linear score on the horizontal axis to a probability between zero and one on the vertical axis, showing the characteristic S shape crossing 0.5 at a score of zero. Linear score z = w·x + b Probability P(y = 1) 1.0 0.5 0.0
Figure 1. The sigmoid function σ(z) = 1 / (1 + e−z). A score of zero maps to probability 0.5; large positive scores approach 1 and large negative scores approach 0, but the output never leaves the interval.

How to study this unit

Keep Unit 4 open beside you. Almost everything here is a modification of something you already know: the same weighted sum of features, the same gradient descent, the same train/test discipline. What changes is the link function and the loss. If you can say precisely what changed and why, you have understood the unit.

02 Learning outcomes

By the end of Unit 5 you should be able to do everything listed below without referring back to the notes. These outcomes are the ones the quiz and Assignment 3 are written against.

Knowledge

  • Explain why linear regression is unsuitable for binary targets and what specifically goes wrong when you try.
  • Describe the sigmoid function, its range and its shape, and explain why it converts a score into a valid probability.
  • Relate probabilities to odds and log-odds, and explain why logistic regression is linear in the log-odds rather than in the probability.
  • Distinguish the decision boundary from the decision threshold, and explain how each is determined.
  • State why logistic regression is fitted by maximum likelihood and what the resulting cross-entropy loss penalises.

Skills

  • Prepare a dataset for binary classification: encode the target, handle class imbalance, and check for leakage.
  • Fit a logistic regression model with scikit-learn and recover predicted probabilities using predict_proba.
  • Interpret coefficients as odds ratios and explain what a unit change in a feature does to the odds.
  • Choose and justify a classification threshold based on the relative cost of false positives and false negatives.
  • Plot and read a decision boundary for one- and two-feature models.

Professional competencies

  • Explain to a non-technical stakeholder why a predicted probability of 0.7 is not a statement of fact.
  • Recognise when a threshold other than 0.5 is ethically or commercially required.
  • Identify proxy discrimination in a classification pipeline — for example, postcode standing in for ethnicity in a loan model.

Prerequisites assumed by this unit

  • Unit 4 — the linear model, weights and bias, cost functions, gradient descent.
  • Basic probability — the idea of an event, and that probabilities lie between 0 and 1.
  • Logarithms and exponentials at the level of ex and ln(x).

If log-odds are unfamiliar, Tutorial 4 builds them from first principles using only odds and a logarithm. No prior exposure is assumed.

03 Reading roadmap

Work through the tutorials in order. Tutorials 5 and 6 are the conceptual centre of the unit — do not rush them, because the threshold decision in Tutorial 5 is the part practitioners most often get wrong.

Unit 5 study sequence
Tutorial Title Core focus Est.
t-01 From Regression to Classification Binary targets, why squared error breaks, the shape of the problem 25 min
t-02 Binary Outcomes and Probability Bernoulli targets, predicted probability, calibration 30 min
t-03 The Sigmoid Function σ(z), range and shape, why it produces valid probabilities 30 min
t-04 Odds, Log-Odds and the Logit Transformation Odds ratios, why the model is linear in log-odds 30 min
t-05 Decision Boundaries and Thresholds Where the boundary comes from, choosing a threshold, cost asymmetry 35 min
t-06 Fitting the Model: Maximum Likelihood and Cross-Entropy Likelihood, log-loss, gradient descent for logistic regression 35 min
t-07 Worked Example: Customer Churn End-to-end scikit-learn pipeline, class imbalance, threshold tuning 30 min
t-08 Worked Example: Loan Approval Interpretation, proxy variables, fairness and regulatory context 30 min
Total guided study time ≈4 h

Suggested study sequence

  1. Read the concept, don't skim it Sections 1–5 of each tutorial carry the idea. Slow down on the worked example.
  2. Run the code yourself Every notebook is short. Type it out at least once before you copy-paste it.
  3. Do the self-check before the answer reveal Section 7 exists to catch the misunderstanding while it is still cheap to fix.
  4. Attempt the practice exercises and problem set Sections 8 and 9 are where the skill actually forms.
  5. Write two sentences in the discussion Section 10 asks you to reason about the classifier, not just run it.

04 Tutorials

Eight self-contained pages. Each follows the same twelve-section structure — objectives, motivating example, concept, visual, worked example, interactive activity, self-check, practice exercises, problem set, discussion, summary and further reading.

Running example used throughout

Tutorials 1–6 use a small synthetic churn dataset so the arithmetic stays visible and the boundary can be plotted on screen. Tutorials 7 and 8 switch to real, imbalanced, messier data — and to the ethical questions that come with it.

05 Learning activities

Reading alone will not get you to the outcomes. These are the activities that will.

Guided notebooks Eight short notebooks (nb-09 … nb-16), one per tutorial. Runnable in Jupyter, Colab or any local environment with NumPy, pandas, Matplotlib and scikit-learn.
Threshold slider Drag the decision threshold from 0.05 to 0.95 and watch the confusion matrix change in real time. Used in Tutorial 5 to make the precision–recall trade-off tangible.
Discussion prompts Two short written prompts per unit. Graded on reasoning quality, not length.
Cost-benefit worksheet Given a stated cost per false positive and false negative, calculate the threshold that minimises expected cost. Used in Tutorials 5 and 8.

Interactive activity — pick a threshold, defend it

In the Tutorial 5 notebook, a churn classifier produces predicted probabilities for 1,000 held-out customers. The company retains a customer at a cost of $40, and loses $600 in revenue when one leaves.

  1. Using only the training data, compute the expected cost at thresholds 0.1, 0.3, 0.5 and 0.7.
  2. Which threshold minimises expected cost? How far is it from 0.5?
  3. Now suppose the retention offer costs $250 instead. How does the optimal threshold move, and why?
  4. Write one sentence justifying your final choice to a non-technical manager.
nb-13 · Probabilities, not labels Compare predict against predict_proba and see how much information the threshold throws away.
import numpy as np
from sklearn.linear_model import LogisticRegression

# Features: [months_as_customer, monthly_charge], target: churned?
X = np.array([[24, 45.0], [3, 92.5], [48, 38.0], [7, 88.0], [36, 52.5]])
y = np.array([0, 1, 0, 1, 0])

clf = LogisticRegression().fit(X, y)

print("probabilities:", clf.predict_proba(X)[:, 1].round(3))
print("labels @ 0.5  :", clf.predict(X))
print("odds ratio    :", np.exp(clf.coef_[0]).round(3))
probabilities: [0.062 0.918 0.041 0.865 0.103]
labels @ 0.5  : [0 1 0 1 0]
odds ratio    : [0.943 1.121]

The odds ratio on monthly_charge is 1.121: each additional dollar of monthly charge multiplies the odds of churn by about 1.12, holding tenure constant. Note that this is a multiplicative effect on odds — not an additive effect on probability.

06 Assessment

Unit 5 contributes to your grade through one quiz and one assignment. Both are mapped directly onto the learning outcomes in Section 02.

0%

Self-checks & practice

Embedded in every tutorial. Formative only — they exist to tell you what you have misunderstood before the graded work.

5%

Quiz 2.2

15 questions, 30 minutes, auto-marked, unlimited attempts until the deadline. Covers Tutorials 1–6.

10%

Assignment 3 — Classification Analysis

A short report on a binary classification dataset: model fit, threshold justification, error analysis and fairness commentary.

What the quiz will ask you to do

Outcome Question type Items
Regression vs. classification, why squared error fails Multiple choice, conceptual reasoning 3
Probability, odds and log-odds Calculation, short answer 4
The sigmoid function and its properties Multiple choice, interpret a plot 3
Decision boundaries and thresholds Scenario reasoning, choose a threshold 3
Maximum likelihood and cross-entropy Multiple choice, short answer 2
Total 15

Assignment 3 — Classification Analysis

  • Part A Problem framing and data preparation — target definition, class balance, leakage check Unit 5
  • Part B Model fitting and evaluation — probabilities, metrics, confusion matrix Unit 6
  • Part C Threshold justification and fairness analysis — costs, trade-offs, proxy variables Unit 5

Academic integrity

You may discuss approaches with classmates, but the notebook and the written analysis must be your own. Any dataset, code fragment or figure you did not produce must be cited.

07 Summary

Unit 5 in one paragraph

Logistic regression predicts the probability that a binary target belongs to the positive class. It computes the same weighted sum of features as linear regression, then passes that score through the sigmoid function to constrain the output to the interval (0, 1). Because the model is linear in the log-odds, each coefficient can be read as the change in log-odds per unit change in its feature, or exponentiated into an odds ratio. The model is fitted by maximum likelihood, which is equivalent to minimising the cross-entropy loss — a convex objective, so gradient descent converges reliably. Crucially, the predicted probability is not the decision: a threshold must be chosen, and that choice should follow from the relative costs of false positives and false negatives, not from a reflexive use of 0.5.

Key terms

Binary classification
A supervised learning task in which the target has exactly two possible values, conventionally encoded as 0 and 1.
Sigmoid (logistic) function
The function σ(z) = 1 / (1 + e−z), which maps any real number to a value strictly between 0 and 1.
Odds
The ratio p / (1 − p). If the probability of churn is 0.8, the odds are 4 to 1.
Log-odds (logit)
The natural logarithm of the odds, ln(p / (1 − p)). Logistic regression is a linear model in this quantity.
Odds ratio
exp(wⱼ), the factor by which the odds change for a one-unit increase in feature j, holding all other features constant.
Decision boundary
The set of points where the predicted probability equals the threshold — for a two-feature model, a straight line.
Decision threshold
The probability cut-off above which the model predicts the positive class. A modelling choice, not a property of the data.
Maximum likelihood
The fitting principle that chooses the parameters which make the observed labels most probable under the model.
Cross-entropy (log-loss)
The loss function obtained by taking the negative log-likelihood. It penalises confident wrong predictions very heavily.

You are ready to move on when…

  • You can explain why squared error is a poor loss for a binary target, without notes.
  • You can convert between probability, odds and log-odds fluently.
  • You can look at a confusion matrix and say whether the threshold was too high or too low.
  • You can justify a non-default threshold using a stated cost structure.

Ready to build a classifier?

Tutorial 1 starts with the question that separates classification from regression: what does it actually mean for a model to output a probability?

👤