COMP328 Fundamentals of Machine Learning

Module 2 · Unit 4

Supervised Learning Linear Regression

Build your first predictive model. This unit takes you from the idea of a prediction problem, through the mathematics of least squares and the geometry of the loss surface, to a fully fitted, evaluated and honestly interpreted regression model in scikit-learn.

8 tutorials ≈4 hours guided study 1 quiz 1 assignment

01 Why this unit

Linear regression is the smallest complete machine learning system. It has a model, a loss function, an optimisation procedure and an evaluation story — and every one of those parts reappears, at larger scale, in the deep networks you will meet in Module 5.

Because the mathematics stays simple, this is the unit where you can see the whole machine at once. If you understand precisely what least squares is minimising, why the loss surface is shaped like a bowl, and what a residual plot is telling you, then the later algorithms in this course stop being a list of tricks and start being variations on a theme you already know.

What makes this unit different

  • Prediction, not classification. The target is a number on a continuous scale, not a label.
  • Interpretable by construction. Each weight is a statement about how much one feature moves the prediction.
  • Analytically solvable. You can derive the answer with calculus or find it iteratively — and compare the two.
  • A baseline that is hard to beat. Many production teams ship linear models precisely because they are cheap, stable and explainable.
Scatter plot of data points with a fitted regression line A set of observed data points plotted against a horizontal feature axis and a vertical target axis, with a straight line of best fit passing through the cloud of points. Feature x Target y
Figure 1. A fitted linear model. The line is chosen so that the vertical distances from the points to the line — the residuals — are as small as possible in aggregate.

How to study this unit

Do not read all eight tutorials in one sitting. Each one ends with a worked example and a self-check; run the code, change a number, and break the model on purpose. Regression is learned in the notebook, not in the reading.

02 Learning outcomes

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

Knowledge

  • Explain the difference between regression and classification, and identify which one a given problem requires.
  • Describe a linear model in terms of features, weights and a bias term, and read the hypothesis function as a weighted sum of evidence.
  • State precisely what the least-squares criterion minimises and why the resulting loss surface is convex.
  • Distinguish the closed-form normal equation from iterative gradient descent, and explain the trade-offs between them.

Skills

  • Prepare a dataset for regression: separate features from target, handle missing values, encode categorical variables and scale where appropriate.
  • Fit a linear regression model using scikit-learn and recover the learned coefficients.
  • Evaluate a model with RMSE, MAE and R², and explain when each metric is the right one to report.
  • Diagnose underfitting and overfitting using residual plots, learning curves and a held-out test set.

Professional competencies

  • Communicate a model's predictions and its limitations to a non-technical audience.
  • Recognise when a linear model is inappropriate and say so, rather than reporting a number anyway.
  • Identify data leakage, proxy variables and fairness concerns in a regression pipeline.

Prerequisites assumed by this unit

  • Basic Python — variables, functions, lists, importing a library.
  • Introductory statistics — mean, variance, correlation, scatter plots (COMP268).
  • Basic algebra — straight lines, summation notation, and the idea of a derivative.

If derivatives are rusty, the refresher box in Tutorial 5 is sufficient — no calculus course is required.

03 Reading roadmap

Work through the tutorials in order. Each one assumes the vocabulary introduced by the previous one, and Tutorials 7 and 8 assume you can already fit and evaluate a model.

Unit 4 study sequence
Tutorial Title Core focus Est.
t-01 Prediction Problems and Regression Continuous targets, regression vs. classification, framing a question 25 min
t-02 The Linear Model: Features, Weights and Bias Hypothesis function, notation, matrix form 30 min
t-03 The Least-Squares Method Residuals, RSS, the closed-form solution 35 min
t-04 The Cost Function and the Loss Surface MSE, convexity, contour and surface plots 30 min
t-05 Fitting the Model: Gradient Descent and the Normal Equation Learning rate, convergence, when to use which 35 min
t-06 Evaluating and Diagnosing a Regression Model RMSE, MAE, R², residual plots, overfitting 30 min
t-07 Worked Example: House Price Prediction End-to-end scikit-learn pipeline 30 min
t-08 Worked Example: Student Grade Prediction Interpretation, fairness, honest reporting 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 model, 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 dataset so that the arithmetic stays visible. Tutorials 7 and 8 switch to real, messier data — because the gap between a clean example and a real one is where most of the learning happens.

05 Learning activities

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

Guided notebooks Eight short notebooks (nb-01 … nb-08), one per tutorial. Runnable in Jupyter, Colab or any local environment with NumPy, pandas, Matplotlib and scikit-learn.
Interactive loss explorer Drag the slope and intercept of a line and watch the MSE change in real time. Used in Tutorials 3 and 4 to build intuition for the loss surface.
Discussion prompts Two short written prompts per unit. Graded on reasoning quality, not length.
Peer code review Swap your Assignment 2 notebook with a partner and check it against the diagnostic checklist in Tutorial 6.

Interactive activity — break the model on purpose

In the Tutorial 4 notebook, fit a linear model to data that is clearly curved. Record the R², then plot the residuals. Repeat with a single extreme outlier added to the training set.

  1. What does R² tell you in each case?
  2. What does the residual plot tell you that R² does not?
  3. Which failure would you rather have a model make, and why?
nb-03 · Least squares from scratch Implement the normal equation with NumPy, then compare against LinearRegression from scikit-learn.
import numpy as np
from sklearn.linear_model import LinearRegression

# Features: [size_m2, bedrooms], target: price in thousands
X = np.array([[62, 2], [85, 3], [104, 3], [128, 4], [150, 4]])
y = np.array([210, 275, 330, 402, 455])

model = LinearRegression().fit(X, y)

print("weights :", model.coef_.round(2))
print("bias    :", round(model.intercept_, 2))
print("R²      :", round(model.score(X, y), 4))
weights : [ 2.86  5.71]
bias    : 36.9
R²      : 0.9979

The weight on size_m2 says: holding bedrooms constant, each extra square metre is associated with about 2.86 thousand more in price. That sentence — not the R² — is usually what a stakeholder actually wants.

06 Assessment

Unit 4 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.1

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

10%

Assignment 2 — Regression Modelling

A short report on a dataset of your choice: cleaning decisions, model fit, evaluation and an honest limitations section.

What the quiz will ask you to do

Outcome Question type Items
Regression vs. classification Multiple choice, scenario matching 3
Linear model notation and interpretation Multiple choice, short answer 4
Least squares and the cost function Conceptual reasoning, calculation 4
Fitting and convergence Multiple choice, short answer 2
Evaluation and diagnosis Interpret a residual plot, choose a metric 2
Total 15

Assignment 2 — Regression Modelling

  • Part A Data exploration and preparation — features, target, missing values, leakage check Unit 4
  • Part B Model fitting and evaluation — train/test split, metrics, residual analysis Unit 6
  • Part C Interpretation and limitations — coefficient reading, fairness and reporting Unit 6

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 4 in one paragraph

Linear regression predicts a continuous target as a weighted sum of features plus a bias term. The weights are chosen by minimising the residual sum of squares — equivalently, the mean squared error — which produces a convex loss surface with a single global minimum. That minimum can be found analytically with the normal equation or iteratively with gradient descent. Because the model is simple, it is easy to fit, easy to interpret and easy to get wrong: the real skill lies in preparing the data honestly and diagnosing the fitted model with residuals, held-out data and a clear-eyed reading of its limits.

Key terms

Hypothesis function
The function h(x) that maps a feature vector to a predicted target value. For linear regression, h(x) = w·x + b.
Residual
The difference between an observed target and the model's prediction for that example: eᵢ = yᵢ − ŷᵢ.
Residual sum of squares (RSS)
The sum of all squared residuals across the training set. Least squares minimises this quantity.
Cost function
A function of the model parameters that measures how wrong the model is. Training means finding the parameters that minimise it.
Convexity
A property of the MSE loss surface for linear regression: any local minimum is the global minimum, so gradient descent cannot get stuck.
Normal equation
The closed-form solution w = (XᵀX)⁻¹Xᵀy, which gives the least-squares weights directly, without iteration.
R² (coefficient of determination)
The proportion of variance in the target explained by the model, relative to predicting the mean. Not a measure of correctness.

You are ready to move on when…

  • You can explain, without notes, what least squares minimises and why the loss surface is a bowl.
  • You can look at a residual plot and say whether the linear assumption is reasonable.
  • You can fit, evaluate and critique a regression model in under thirty minutes.

Ready to build your first model?

Tutorial 1 starts with the question every machine learning project begins with: what exactly are we trying to predict, and why?

👤