- Unit 4 · Linear Regression
- Unit 5 · Logistic Regression
- Unit 6 · Model Evaluation
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.
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-learnand 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.
| 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
-
Read the concept, don't skim it Sections 1–5 of each tutorial carry the idea. Slow down on the worked example.
-
Run the code yourself Every notebook is short. Type it out at least once before you copy-paste it.
-
Do the self-check before the answer reveal Section 7 exists to catch the misunderstanding while it is still cheap to fix.
-
Attempt the practice exercises and problem set Sections 8 and 9 are where the skill actually forms.
-
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.
Prediction Problems and Regression
Distinguish regression from classification, identify continuous targets, and turn a vague question into a well-posed prediction problem.
t-02The Linear Model: Features, Weights and Bias
Build the hypothesis function h(x) = w·x + b and learn to read it as a weighted sum of evidence with a baseline offset.
t-03The Least-Squares Method
Define residuals and the residual sum of squares, then derive the closed-form least-squares solution.
t-04The Cost Function and the Loss Surface
Read mean squared error as a cost function, plot the loss surface, and see why it has exactly one minimum.
t-05Fitting the Model: Gradient Descent and the Normal Equation
Minimise the cost iteratively, tune the learning rate, and know when the analytical solution is the better choice.
t-06Evaluating and Diagnosing a Regression Model
RMSE, MAE and R², residual plots, learning curves, and how to spot underfitting, overfitting and leakage.
t-07Worked Example: House Price Prediction
A complete scikit-learn pipeline on a housing dataset — cleaning, encoding, fitting, evaluating and interpreting the coefficients.
t-08Worked Example: Student Grade Prediction
A second end-to-end build, with close attention to proxy variables, fairness and reporting a model honestly.
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.
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.
- What does R² tell you in each case?
- What does the residual plot tell you that R² does not?
- Which failure would you rather have a model make, and why?
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.
Self-checks & practice
Embedded in every tutorial. Formative only — they exist to tell you what you have misunderstood before the graded work.
Quiz 2.1
15 questions, 30 minutes, auto-marked, unlimited attempts until the deadline. Covers Tutorials 1–6.
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?