COMP328 Fundamentals of Machine Learning

1 Learning objectives

By the end of this tutorial you will be able to

  • Write the hypothesis function for a linear model with any number of features, in both sum notation and vector notation.
  • Interpret each weight as a partial effect — the change in the prediction per unit change in its feature, holding all other features constant.
  • Explain what the bias (intercept) term does and why omitting it constrains the model in a way that is usually undesirable.
  • Distinguish linear in the parameters from linear in the features, and explain why only the former matters for a linear model.
  • Build the augmented design matrix by prepending a column of ones, and write the model compactly as ŷ = Xw.
  • Compute predictions by hand from a fitted model, and reason about how the predictions change under unit changes to features or weights.
  • Explain how feature scaling changes the numerical values of the weights without changing the model's predictions.
  • State the principal limitations of the linear model and recognise when a linear form is inappropriate.

Estimated time

30 minutes of reading, plus 20–25 minutes for the practice exercises and problem set. The notation introduced here is used in every subsequent tutorial in this course, so it is worth getting comfortable with it now.

2 Motivating example

Tutorial 1 left us with a well-posed problem: predict the number of bike rentals at a station in the next hour, from features that will be known at the time the prediction is made.

We have a target, we have features, and we have a baseline. What we do not yet have is a model — a specific mathematical form that takes a feature vector and produces a prediction. There are infinitely many such forms. We could predict that rentals equal the square root of temperature, or that they oscillate sinusoidally with the hour of the day, or that they depend on some complicated interaction between the two.

The linear model is the simplest of these forms, and it is the one we will start with. It says: the prediction is a weighted sum of the features, plus a constant.

That is all it says. There is no hidden structure, no clever transformation, no interaction between features. Each feature contributes independently, in proportion to its value, scaled by its own weight. The model then adds everything up.

ŷ = w₁x₁ + w₂x₂ + … + wdxd + b

For the bike-share problem with a single temperature feature, this reduces to the equation of a straight line: ŷ = wx + b. With two features it becomes a flat plane in three dimensions. With many features it is a flat hyperplane in a space you cannot draw — but the arithmetic is unchanged.

You have seen this equation before, in secondary school algebra. What is new is not the mathematics. What is new is the interpretation: the weights are not arbitrary numbers to be found, they are statements about the data, and reading them correctly is most of what makes a linear model useful in practice.

What the linear model gives you

  • A prediction for any feature vector
  • Coefficients you can explain in plain language
  • A form that is cheap to compute and cheap to store
  • A fitting problem with a closed-form solution

What it costs you

  • No interactions between features unless you construct them
  • No curvature — the effect of a feature is constant across its range
  • Very sensitive to outliers and to correlated features
  • Extrapolates badly outside the observed range

3 Concept explanation

3.1 The hypothesis function

A supervised model is a function that maps a feature vector to a prediction. That function is called the hypothesis, written h(x), and it is parameterised by the weights and the bias.

Linear hypothesis function

Sum form: hw,b(x) = w₁x₁ + w₂x₂ + … + wdxd + b

Compact sum: hw,b(x) = Σj=1d wjxj + b

Vector form: hw,b(x) = wᵀx + b

The subscript on h records the fact that the function depends on the parameters. Change the weights and you get a different hypothesis from the same family. Fitting or training the model means choosing the specific w and b that make the hypothesis fit the training data well. That is the subject of Tutorials 3, 4 and 5.

This tutorial is about the family itself — what it can represent, what the parameters mean, and how to write it down efficiently.

3.2 What a weight means

Take the weight wj. It multiplies the feature xj. To understand what it does, ask what happens when xj increases by one unit while every other feature is held constant. The prediction changes by exactly wj, because wj is the only term in the sum that involves xj.

The interpretation of a coefficient

wj is the change in the predicted target per one-unit increase in feature j, holding all other features fixed.

Three things are worth noticing about that sentence:

  • "holding all other features fixed" is essential. With multiple features the coefficient is a partial effect. If two features move together in the data, each coefficient describes what happens when only one of them changes — a situation that may never occur in reality. This is why interpreting coefficients from observational data as causal effects is dangerous.
  • The units matter. wj carries the units of the target divided by the units of the feature. A coefficient of 20.65 in a model predicting rentals from temperature is measured in "rentals per degree Celsius". Change the feature to Fahrenheit and the coefficient changes; the predictions do not.
  • The sign is meaningful. A positive coefficient means the feature pushes the prediction up; a negative coefficient pushes it down. Both are informative, and a sign that contradicts domain knowledge is usually a signal that something is wrong with the data or the framing.

3.3 The bias term

The parameter b is called the bias, the intercept, or the offset. It is the value the model predicts when every feature is exactly zero:

h(0) = b

Its role is to let the model shift up or down without changing any of the slopes. Without it, the model would be forced to pass through the origin: if all features are zero, the prediction must be zero. That is occasionally the right constraint — if you are predicting a distance from a known starting point, for example — but it is wrong far more often than it is right.

The intercept is often not physically meaningful

In the bike-share model, the fitted intercept is around −62.6 rentals. That would mean the model predicts negative rentals at 0 °C, which is obviously impossible. This is not a defect in the model. It is a reminder that the intercept describes the value of the line where it meets the y-axis, and that point is often far outside the range of the data.

The observed temperatures run from 8 °C to 30 °C. The intercept lives at 0 °C, which is extrapolation. Do not interpret it. If you want an interpretable constant, centre the feature first — subtract the mean so that zero corresponds to the average temperature — and the intercept becomes the prediction at the average.

Mechanically, the bias is easy to overlook because it is not attached to any feature. The cleanest way to handle it is to pretend it is attached to a feature that is always equal to 1. That is exactly what the augmented design matrix does, in Section 3.6.

3.4 From one feature to many

With a single feature, the model is a line: ŷ = wx + b. With two features it is a plane. With three or more it is a hyperplane — a flat surface in a space with as many dimensions as there are features.

The arithmetic does not change. You multiply each feature by its weight, add the results, and add the bias. What changes is only how many terms there are.

The same model at increasing numbers of features
Features Hypothesis Geometric shape
1 ŷ = w₁x₁ + b A line in the plane
2 ŷ = w₁x₁ + w₂x₂ + b A plane in three-dimensional space
3 ŷ = w₁x₁ + w₂x₂ + w₃x₃ + b A three-dimensional hyperplane in four-dimensional space
d ŷ = Σ wjxj + b A (d−1)-dimensional hyperplane in d+1 dimensions

The word hyperplane sounds intimidating, but it just means "flat". A hyperplane in four dimensions is no more conceptually difficult than a plane in three; you simply cannot picture it. The algebra is identical, and the vector notation of the next section makes that explicit.

3.5 Vector notation

Writing out a sum with a dozen terms is tedious and error-prone. The vector form is compact and generalises to any number of features:

hw,b(x) = wᵀx + b

Here w = [w₁, w₂, …, wd]ᵀ is the weight vector and x = [x₁, x₂, …, xd]ᵀ is the feature vector for one example. wᵀx is the dot product:

wᵀx  =  w₁x₁ + w₂x₂ + … + w_d x_d

      ⎡ x₁ ⎤
   =  [w₁ w₂ … w_d] ⎢ x₂ ⎥  =  a single number
      ⎢ ⋮  ⎥
      ⎣ x_d⎦

The dot product has a useful geometric interpretation: it measures how much the feature vector aligns with the weight vector. Features whose values point in the same direction as their weights contribute positively to the prediction; features pointing against their weights contribute negatively. A large weight on a feature that is irrelevant to the target will do nothing if that feature's values are consistently near zero — which is why feature selection matters.

3.6 The augmented design matrix

Carrying the bias term separately through every derivation is awkward. The standard trick is to absorb it into the weight vector by introducing an extra feature that is always equal to 1.

Define:

x₀ = 1,    w₀ = b

Then the model becomes a pure dot product with no separate constant:

h(x) = w₀x₀ + w₁x₁ + … + wdxd = wᵀx

For the whole dataset at once, stack the feature vectors into the design matrix X:

      ⎡ 1  x₁₁  x₁₂  ⋯  x₁d ⎤         ⎡ w₀ ⎤          ⎡ y₁ ⎤
X  =  ⎢ 1  x₂₁  x₂₂  ⋯  x₂d ⎥ ,   w = ⎢ w₁ ⎥ ,   y =  ⎢ y₂ ⎥
      ⎢ ⋮   ⋮    ⋮   ⋱   ⋮  ⎥         ⎢ ⋮  ⎥          ⎢ ⋮  ⎥
      ⎣ 1  xₙ₁  xₙ₂  ⋯  xₙd ⎦         ⎣ wd ⎦          ⎣ yₙ ⎦

                    ŷ  =  X w          (n × 1)

The design matrix has n rows — one per training example — and d+1 columns: a leading column of ones for the bias, plus one column per feature. The predictions for all n examples come from a single matrix–vector product.

Why the column of ones works

In row i of Xw, the first term of the dot product is 1 × w₀ = b. So every prediction automatically receives the same additive constant, exactly as the original formula required. The bias has not disappeared — it has simply been given a feature to attach to.

This convention is used everywhere: in the normal equation of Tutorial 3, in the matrix form of the gradient in Tutorial 4, and in every implementation of linear regression you will encounter.

3.7 What "linear" actually means

This is the point in the course where the word linear most often causes confusion, so it is worth being precise.

A linear model is linear in its parameters. It is not necessarily linear in the features.

Consider the model:

ŷ = w₀ + w₁x + w₂x²

Plotted against x, this is a parabola — clearly curved. But as a function of the parameters w₀, w₁ and w₂, it is a weighted sum. Define x₁ = x and x₂ = x², and it becomes exactly the linear model from Section 3.1. The weights enter linearly, so every technique in this unit applies without modification.

Linear in the parameters, or not?
Model Linear in features? Linear in parameters? Fitted by linear regression?
ŷ = w₀ + w₁x Yes Yes Yes
ŷ = w₀ + w₁x + w₂x² No Yes Yes
ŷ = w₀ + w₁x₁ + w₂x₁x₂ No Yes Yes
ŷ = w₀ + sin(w₁x) No No No
ŷ = w₀ + w₁²x Yes No No
ŷ = 1 / (1 + e−w₁x) No No No

The practical consequence is large. By constructing new features — squares, logs, products, indicator variables — you can fit a rich family of curved and interacting relationships using nothing more than the linear machinery of this unit. The engineering effort moves from the optimisation to the feature construction, which is where a great deal of applied machine learning actually happens.

More features is not free

Adding polynomial or interaction terms increases the number of parameters, and with it the risk of overfitting — fitting the noise in the training data rather than the signal. The bias–variance tradeoff of Tutorial 7 is exactly about this tension. For now, note that a linear model with fifty engineered features is still a linear model, and still subject to every limitation discussed in the next section.

3.8 Scaling changes the weights, not the model

Suppose you measure temperature in Celsius and fit the bike-share model, obtaining a slope of about 20.65 rentals per degree. Now convert the feature to Fahrenheit and refit. The new slope will be approximately 20.65 / 1.8 ≈ 11.47, because a one-degree change in Fahrenheit is a smaller physical change than one degree Celsius.

The predictions are identical. The model has not changed; only its parameterisation has. This has two consequences worth internalising:

  • You cannot compare coefficient magnitudes across features measured in different units. A coefficient of 1,000 on a feature measured in millimetres and a coefficient of 1 on a feature measured in metres may represent the same physical effect. If you want to compare the relative importance of features, standardise them first — then all the coefficients are on the same scale.
  • Feature scaling changes the loss surface. Tutorial 4 will show that the conditioning of the surface depends on the scale of the features, and Tutorial 5 will demonstrate that gradient descent can need tens of thousands of times more iterations on unscaled features than on scaled ones. The model is unchanged; the difficulty of finding it is not.

3.9 Limits of the linear model

A linear model assumes that the effect of each feature on the target is additive and constant. Both assumptions are often wrong.

Four things a plain linear model cannot represent
Limitation What it means Partial remedy
Non-linearity The effect of a feature changes over its range — for example, rentals rise steeply with temperature up to about 25 °C and then flatten. Add polynomial or spline features: x², x³, or piecewise terms.
Interactions The effect of one feature depends on another — rain suppresses the effect of temperature. Add product features: x₁x₂.
Outlier sensitivity A single extreme observation can dominate the fit, because squared error grows quadratically. Robust regression, or least absolute deviations.
Extrapolation Outside the observed range, the constant-effect assumption is unlikely to hold and the prediction becomes unreliable. None, within the linear framework. Report predictions beyond the observed range with explicit caution.

The remedies in the third column all keep the model linear in its parameters, which means everything you learn in the rest of this unit still applies. But each one adds parameters, and each one therefore moves you closer to the overfitting problem. The discipline is to add complexity only when the residuals demand it — which is the subject of Tutorial 6.

A linear model fitted to non-linear data is not "wrong"

It is a straight line through curved data. It will still produce predictions, and those predictions may be perfectly adequate within a narrow range. What it will not do is tell you that it is struggling. That is what residual plots are for, and that is why Tutorial 6 exists. Never report a linear model's performance without looking at its residuals.

4 Visual illustration

A straight line with its intercept and slope annotated A straight line drawn on a set of axes. The point where the line crosses the vertical axis is labelled as the intercept b. A right-angled triangle drawn on the line shows a horizontal run and a vertical rise, whose ratio is the slope w. b — the intercept the prediction when every feature is 0 run = 1 unit of x rise = w slope = w change in ŷ per unit change in x Feature x Prediction ŷ ŷ = w x + b
Figure 1. The single-feature linear model. The intercept b is where the line crosses the vertical axis; the slope w is the rise over the run — how much the prediction changes for each one-unit increase in the feature. Every straight line is fully described by these two numbers.
Diagram of a linear model as a weighted sum of features plus a bias Three feature boxes labelled x1, x2 and x3 each connect by an arrow to a central summation node. Each arrow is labelled with its corresponding weight, w1, w2 and w3. A fourth box labelled b, the bias, also connects to the summation node. A single arrow leaves the summation node and points to an output box labelled with the prediction y-hat. x₁ x₂ x₃ 1 × w₁ × w₂ × w₃ × b Σ ŷ the extra unit feature carries the bias, so the whole model is one dot product
Figure 2. The linear model as a weighted sum. Each feature is multiplied by its own weight, all the products are added together, and the bias contributes a constant. Introducing a feature that is always 1 lets the bias be treated on exactly the same footing as every other term.
Two-feature linear model as a tilted plane with data points A three-dimensional coordinate frame with two horizontal feature axes and a vertical target axis. A tilted parallelogram represents the set of predictions the linear model can make. Two data points are plotted above and below the plane, with dashed vertical lines showing the residuals between each point and the plane. b vertical gap = residual actual y minus predicted ŷ Feature x₁ Feature x₂ Target y ŷ = w₁x₁ + w₂x₂ + b two features → a flat plane; the model cannot bend
Figure 3. With two features the linear model is a plane. Every possible prediction lies on this flat surface. The blue dots mark where the plane predicts for two particular feature combinations; the green dots are the observed values. The dashed vertical segments are the residuals the model makes.
Two models that are both linear in their parameters Two panels showing the same scatter of data points. In the left panel a straight line has been fitted. In the right panel a parabola has been fitted to the same points. Both models are linear in their parameters, so both can be fitted by the same linear regression machinery. ŷ = w₀ + w₁x straight line — the model bends nowhere systematic residual pattern visible ŷ = w₀ + w₁x + w₂x² curved — but still a linear model residuals now look like noise Both are fitted by the same least-squares machinery — the second simply uses x and x² as two features.
Figure 4. "Linear" refers to the parameters, not the shape of the curve. Adding x² as a second feature lets the same linear machinery fit a parabola. The left panel shows a straight fit with a visible systematic residual pattern; the right panel shows the polynomial fit, whose residuals look like noise. Nothing about the fitting procedure changed.

5 Worked example

We will build and interpret a two-feature linear model for the bike-share problem, then compute predictions by hand and reason about what the coefficients mean.

Step 1 — Specify the model

Suppose we have two features available at prediction time:

  • x₁ — forecast temperature in degrees Celsius
  • x₂ — an indicator that equals 1 on a weekend day and 0 on a weekday

The hypothesis function is:

ŷ = w₁x₁ + w₂x₂ + b

Suppose that fitting this model to historical data — a process we will carry out properly in Tutorial 3 — gives the coefficients:

w₁  =  18.40      rentals per °C
w₂  =  62.50      rentals on weekends vs weekdays
b   = −40.20      rentals

Model:  ŷ = 18.40 · temperature + 62.50 · is_weekend − 40.20

Step 2 — Interpret each coefficient

Reading the coefficients in plain language
Parameter Value Units Interpretation
w₁ 18.40 rentals per °C Each additional degree Celsius is associated with 18.4 more rentals per hour, holding weekend status constant.
w₂ 62.50 rentals On a weekend, the model predicts 62.5 more rentals than on a weekday at the same temperature.
b −40.20 rentals The prediction for a weekday at 0 °C. Physically impossible, and far outside the observed temperature range — do not interpret it.

Notice how the phrase "holding all other features fixed" does real work in the first two rows. The coefficient on temperature describes the effect of temperature at a fixed weekend status. If weekends were both warmer and busier, a model without the weekend indicator would attribute the weekend effect to temperature, inflating w₁. This is the omitted-variable problem, and it is one of the reasons coefficient interpretation from observational data requires care.

Step 3 — Compute predictions by hand

Case A: a Wednesday at 20 °C.

x₁ = 20 ,  x₂ = 0

ŷ = 18.40(20) + 62.50(0) − 40.20
  = 368.00 + 0 − 40.20
  = 327.80 rentals

Case B: a Saturday at 20 °C.

x₁ = 20 ,  x₂ = 1

ŷ = 18.40(20) + 62.50(1) − 40.20
  = 368.00 + 62.50 − 40.20
  = 390.30 rentals

The difference between the two predictions is exactly w₂ = 62.5 rentals, which is the definition of the weekend coefficient. This is the cleanest way to check that you have understood a coefficient: hold every other feature fixed, change the one you are interested in, and see how much the prediction moves.

Case C: a Sunday at 12 °C.

x₁ = 12 ,  x₂ = 1

ŷ = 18.40(12) + 62.50(1) − 40.20
  = 220.80 + 62.50 − 40.20
  = 243.10 rentals

Step 4 — Compare against the one-feature model

From Tutorial 3, the one-feature model — using only temperature — has coefficients w ≈ 20.65 and b ≈ −62.60, with an RMSE of about 10.2 rentals. The two-feature model will have a lower RMSE, but by how much depends on how much of the variation in rentals the weekend indicator actually explains.

Three observations are worth making:

  • The temperature coefficient fell from 20.65 to 18.40 when the weekend indicator was added. Some of what the one-feature model attributed to temperature was in fact the weekend effect. This is normal and expected.
  • The intercept moved from −62.60 to −40.20. It now refers to a different baseline: a weekday at 0 °C, rather than any day at 0 °C. The intercept is not a stable quantity; it depends entirely on what the "zero" of every feature means.
  • Adding a feature cannot increase the training RMSE. The one-feature model is a special case of the two-feature model with w₂ = 0, so the two-feature model can always match it and usually improves on it. Whether that improvement generalises to new data is a different question, and it is the subject of Tutorials 6 and 7.

Step 5 — Write it in matrix form

Take the four predictions from the table below and assemble the design matrix. For a small dataset of four station-hours:

A four-row dataset with the augmented feature vector
Row x₀ x₁ (temp) x₂ (weekend) y
11200330
21201395
31121248
41120186
      ⎡ 1  20  0 ⎤            ⎡ −40.20 ⎤
X  =  ⎢ 1  20  1 ⎥ ,   w  =   ⎢  18.40 ⎥
      ⎢ 1  12  1 ⎥            ⎣  62.50 ⎦
      ⎣ 1  12  0 ⎦

ŷ = Xw

  ⎡ 1  20  0 ⎤ ⎡ −40.20 ⎤     ⎡ 1(−40.20) + 20(18.40) + 0(62.50)  ⎤     ⎡ 327.80 ⎤
  ⎢ 1  20  1 ⎥ ⎢  18.40 ⎥  =  ⎢ 1(−40.20) + 20(18.40) + 1(62.50)  ⎥  =  ⎢ 390.30 ⎥
  ⎢ 1  12  1 ⎥ ⎢  62.50 ⎥     ⎢ 1(−40.20) + 12(18.40) + 1(62.50)  ⎥     ⎢ 243.10 ⎥
  ⎣ 1  12  0 ⎦ ⎣         ⎦    ⎣ 1(−40.20) + 12(18.40) + 0(62.50)  ⎦     ⎣ 180.60 ⎦

Every row of the output is one prediction, computed as a single dot product. The leading column of ones is doing nothing except adding b = −40.20 to every row, exactly as intended.

The residuals for these four rows are [330−327.80, 395−390.30, 248−243.10, 186−180.60] = [+2.20, +4.70, +4.90, +5.40]. All four are positive, which suggests the model is systematically under-predicting on this small sample. On a larger dataset that pattern would be a warning sign — it is exactly the kind of thing Tutorial 6 teaches you to look for.

The same computation in code

import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression

df = pd.DataFrame({
    "temp_c":     [20, 20, 12, 12],
    "is_weekend": [ 0,  1,  1,  0],
    "rentals":    [330, 395, 248, 186],
})

X = df[["temp_c", "is_weekend"]].to_numpy()
y = df["rentals"].to_numpy()

# --- Route 1: the augmented design matrix, by hand ---
n = len(X)
X_aug = np.column_stack([np.ones(n), X])          # prepend a column of ones

w_aug = np.linalg.solve(X_aug.T @ X_aug, X_aug.T @ y)
b, w1, w2 = w_aug

print(f"by hand  : ŷ = {w1:.2f}·temp + {w2:.2f}·weekend + ({b:.2f})")

# --- Route 2: scikit-learn ---
model = LinearRegression().fit(X, y)
print(f"sklearn  : ŷ = {model.coef_[0]:.2f}·temp "
      f"+ {model.coef_[1]:.2f}·weekend + ({model.intercept_:.2f})")

# --- Predict three cases ---
cases = pd.DataFrame({
    "case":       ["Wed 20°C", "Sat 20°C", "Sun 12°C"],
    "temp_c":     [20, 20, 12],
    "is_weekend": [ 0,  1,  1],
})
cases["predicted"] = model.predict(cases[["temp_c", "is_weekend"]])
print()
print(cases.to_string(index=False))

# --- Fitted values and residuals on the training data ---
df["y_hat"]    = model.predict(X)
df["residual"] = df["rentals"] - df["y_hat"]
print()
print(df.to_string(index=False))
print(f"\nRMSE = {np.sqrt((df['residual'] ** 2).mean()):.2f} rentals")
by hand  : ŷ = 18.40·temp + 62.50·weekend + (-40.20)
sklearn  : ŷ = 18.40·temp + 62.50·weekend + (-40.20)

      case  temp_c  is_weekend  predicted
  Wed 20°C      20           0     327.80
  Sat 20°C      20           1     390.30
  Sun 12°C      12           1     243.10

 temp_c  is_weekend  rentals   y_hat  residual
     20           0      330  327.80      2.20
     20           1      395  390.30      4.70
     12           1      248  243.10      4.90
     12           0      186  180.60      5.40

RMSE = 4.59 rentals

The RMSE of 4.59 rentals is far lower than the one-feature model's 10.2 on the eight-point dataset — but note that these are different datasets of different sizes, so the comparison is not meaningful. The point of this example is the interpretation of the coefficients, not the fit quality.

nb-02 · Building the linear model Construct the design matrix by hand, verify it against scikit-learn, and experiment with adding an interaction term between temperature and the weekend indicator.

6 Interactive activity

Move the line, move the plane

Work through the following in the Tutorial 2 notebook. Each item asks you to predict what will happen before you run the code, then check.

  1. Slope and intercept, separately. Using the eight-point bike-share dataset from Tutorial 1, plot the data and draw the line ŷ = 20.65x − 62.60. Now hold b fixed and increase w to 25. What happens to the line? Now hold w fixed at 20.65 and increase b to 0. What happens? Describe the two effects in words.
  2. Add the weekend feature. Using the four-row two-feature dataset from the worked example, fit the model with and without the weekend indicator. How much does the temperature coefficient change? Why?
  3. Drop the bias. Refit the one-feature model with the intercept forced to zero. What is the new slope? Compute the residuals. Do they sum to zero? Why not?
  4. Change the units. Convert temperature from Celsius to Fahrenheit in the two-feature model and refit. Record the three coefficients. Verify that the predictions for a given physical temperature are unchanged.
  5. Add a polynomial term. Add x² to the one-feature model and refit. Is the model still linear in its parameters? Plot the fitted curve — is it a straight line? What happens to the training RMSE?
  6. Add an interaction. Add the product x₁ × x₂ (temperature times weekend) to the two-feature model. Interpret the new coefficient. What does a non-zero interaction mean in plain language?
Show the discussion
  1. Slope rotates, intercept translates. Increasing w from 20.65 to 25 makes the line steeper — it pivots about the point where it crosses the intercept, so the predictions at high temperature rise and the predictions at low temperature fall. Increasing b from −62.60 to 0 shifts the entire line upward by 62.6 rentals at every temperature, without changing its steepness. These two parameters control two independent aspects of the line: its angle and its height.
  2. The temperature coefficient falls. In the worked example it dropped from about 20.65 to 18.40. Some of the variation the one-feature model attributed to temperature was actually the weekend effect, because weekends may coincide with warmer days in the sample. The two-feature model can separate the two effects, and each coefficient becomes a purer measure of its own feature.
  3. The residuals do not sum to zero. Without an intercept, the line is forced through the origin. Since all the observed rentals are positive and all the temperatures are positive, the constrained line systematically under-predicts and the residuals are all positive. The property Σei = 0 comes from the first normal equation, which only exists when b is a free parameter. Remove it and the property disappears.
  4. All three coefficients change; predictions do not. The temperature coefficient divides by 1.8, becoming about 10.22. The intercept shifts to absorb the offset introduced by the transformation. The weekend coefficient is unchanged, because the weekend feature was not rescaled. Predictions for a given physical temperature are identical to those from the Celsius model to within floating-point precision.
  5. Still linear, but no longer straight. The model ŷ = w₀ + w₁x + w₂x² is linear in its parameters, so least squares applies unchanged. But plotted against x it is a parabola. The training RMSE necessarily falls — you have added a parameter — but whether that improvement is real or merely fitting noise is the question Tutorial 7 answers.
  6. The interaction coefficient measures non-additivity. If the coefficient on x₁x₂ is positive, the effect of temperature is larger on weekends than on weekdays. If it is negative, the effect is smaller. If it is near zero, the two effects are additive and the interaction is not earning its parameter. This is the standard way to test whether two features act independently.

The habit worth building

Every time you add, remove or transform a feature, ask three questions: what happened to the predictions, what happened to each coefficient, and does the change make sense given what I know about the problem? A model whose coefficients you cannot predict the behaviour of is a model you do not yet understand.

7 Self-check questions

Answer each question in your own words before revealing the answer.

Question 1

A model predicting delivery time has the form ŷ = 4.2 · distance − 1.8 · traffic_index + 12.0, where distance is in kilometres and the traffic index runs from 0 (clear) to 10 (gridlocked). Interpret all three numbers, with units.

Show answer
  • 4.2 — each additional kilometre is associated with 4.2 more minutes of delivery time, holding the traffic index constant. Units: minutes per kilometre.
  • −1.8 — each additional point on the traffic index is associated with 1.8 fewer minutes, holding distance constant. Units: minutes per index point. The negative sign is a red flag: heavier traffic should make deliveries slower, not faster. This coefficient contradicts domain knowledge and would need investigation — perhaps the traffic index is measured in a way that inverts its meaning, or there is a confounding variable.
  • 12.0 — the predicted delivery time for a zero-kilometre trip in zero traffic. Units: minutes. Physically meaningless, and outside the range of the data. Do not interpret it.

Question 2

What is the purpose of the bias term, and what happens to the model if you remove it?

Show answer
The bias lets the model shift its predictions up or down without changing any of the slopes. It sets the prediction when every feature equals zero.

Remove it and the model is forced to pass through the origin: if all features are zero, the prediction must be zero. This is occasionally the correct constraint — for example when predicting a distance from a known starting point — but it is usually wrong. The practical consequence is that the residuals will no longer sum to zero, and the fit will be systematically biased whenever the target's natural range does not include zero.

Question 3

A colleague fits the model ŷ = w₀ + w₁ log(x) and says it is "not a linear model because of the logarithm". Are they right?

Show answer
They are wrong, and the distinction matters. The model is not linear in x — it is a curve — but it is linear in the parameters w₀ and w₁. Define a new feature x′ = log(x) and the model becomes ŷ = w₀ + w₁x′, which is exactly the linear model from Section 3.1.

"Linear model" refers to linearity in the parameters, not in the features. Any transformation of the features you like can be applied before fitting, and the least-squares machinery works unchanged. This is why feature engineering is such a powerful tool within the linear framework.

Question 4

A model predicting salary has coefficients 8.2 (years of experience) and 0.4 (age in years). A colleague concludes that experience is twenty times more important than age. What is wrong with that conclusion?

Show answer
Coefficient magnitudes are not comparable across features with different units or different spreads. The coefficient 8.2 is in "salary units per year of experience"; the coefficient 0.4 is in "salary units per year of age". A one-unit change means a different thing for each feature.

Moreover, experience and age are almost certainly highly correlated, so the partial-effect interpretation is fragile — each coefficient describes what happens when that feature changes while the other is held fixed, a situation that rarely occurs. To compare relative importance you would need to standardise both features first, and even then the comparison is confounded by their correlation.

Question 5

Write the linear model with three features in sum notation, vector notation, and matrix notation for a dataset of n examples. What are the dimensions of each object?

Show answer

Sum form, for one example:

ŷ = w₀ + w₁x₁ + w₂x₂ + w₃x₃

Vector form, for one example:

ŷ = wᵀx, where w and x are both length 4 (including the bias).

Matrix form, for all n examples:

ŷ = Xw, where:

  • X is n × 4 — the design matrix with the leading column of ones
  • w is 4 × 1 — the parameter vector
  • ŷ is n × 1 — the vector of predictions

Question 6

Give two reasons why a linear model might produce a physically impossible prediction (such as a negative count), and say what each tells you.

Show answer
  1. Extrapolation. The prediction is being made outside the range of feature values seen in training. The model has no information about what happens there, and the linear form forces a constant effect that may not hold. A negative prediction at 0 °C in the bike-share model is an example: the observed temperatures run from 8 to 30 °C, so the model is guessing about a region it has never seen.
  2. The linear form is simply wrong for the target. Some targets cannot go below zero — counts, prices, durations. A linear model can produce any real number, including impossible ones. This is not a fixable defect in the parameters; it is a mismatch between the model's range and the target's range. The remedies are to transform the target (for example, model log(y) instead of y) or to use a model whose output is naturally constrained, such as the logistic regression of Unit 5 or a count model.

The first case is a warning about the input; the second is a warning about the model family. Both are worth taking seriously, and both are visible in a residual plot if you look.

8 Practice exercises

Work these by hand first, then verify in the notebook.

Exercise 1 — Predictions by hand

A fitted model for house prices (in thousands) is:

ŷ = 2.8 · area_m2 + 15.5 · bedrooms − 0.6 · age_years + 12.0

Compute the predicted price for each house:

House Area (m²) Bedrooms Age (years) Predicted price
A6225
B104318
C15040
D85340

Then answer: house C is brand new. Does the model predict a higher or lower price than an identical house that is 20 years old? By how much?

Show answers

A: 2.8(62) + 15.5(2) − 0.6(5) + 12.0 = 173.6 + 31.0 − 3.0 + 12.0 = 213.6 thousand

B: 2.8(104) + 15.5(3) − 0.6(18) + 12.0 = 291.2 + 46.5 − 10.8 + 12.0 = 338.9 thousand

C: 2.8(150) + 15.5(4) − 0.6(0) + 12.0 = 420.0 + 62.0 − 0.0 + 12.0 = 494.0 thousand

D: 2.8(85) + 15.5(3) − 0.6(40) + 12.0 = 238.0 + 46.5 − 24.0 + 12.0 = 272.5 thousand

Follow-up: a brand-new house is predicted to be 0.6 × 20 = 12 thousand more than an otherwise identical 20-year-old house, because the age coefficient is −0.6 and it multiplies a 20-year difference.

Exercise 2 — Build the design matrix

Using the four houses from Exercise 1, construct the augmented design matrix X and the parameter vector w, and verify that Xw reproduces the four predictions you computed.

Show answers
      ⎡ 1   62  2   5 ⎤            ⎡  12.0 ⎤
X  =  ⎢ 1  104  3  18 ⎥ ,   w  =   ⎢   2.8 ⎥
      ⎢ 1  150  4   0 ⎥            ⎢  15.5 ⎥
      ⎣ 1   85  3  40 ⎦            ⎣  −0.6 ⎦

Row 1:  1(12.0) + 62(2.8) + 2(15.5) + 5(−0.6)
      =  12.0 + 173.6 + 31.0 − 3.0  =  213.6    ✓
Row 2:  1(12.0) + 104(2.8) + 3(15.5) + 18(−0.6)
      =  12.0 + 291.2 + 46.5 − 10.8  =  338.9    ✓
Row 3:  1(12.0) + 150(2.8) + 4(15.5) + 0(−0.6)
      =  12.0 + 420.0 + 62.0 − 0.0  =  494.0    ✓
Row 4:  1(12.0) + 85(2.8) + 3(15.5) + 40(−0.6)
      =  12.0 + 238.0 + 46.5 − 24.0  =  272.5    ✓

Note that the parameter vector places the intercept first, matching the leading column of ones in X. The ordering is a convention; what matters is that the columns of X and the entries of w are in the same order.

Exercise 3 — Linear or not?

For each model below, state whether it is linear in its parameters and whether it could be fitted by ordinary least squares with an appropriate choice of features.

# Model Linear in parameters? Fittable by OLS?
aŷ = w₀ + w₁x
bŷ = w₀ + w₁√x
cŷ = w₀ew₁x
dŷ = w₀ + w₁x₁ + w₂x₁x₂
eŷ = w₀ + w₁x₁ + w₂x₂ + w₃x₁²x₂
fŷ = w₀ + w₁x + w₁²x²
Show answers
  • a — Linear. Fittable by OLS with the feature [1, x].
  • b — Linear. Fittable by OLS with the feature [1, √x].
  • c — Not linear. w₁ appears in an exponent. Not fittable by OLS. This is an exponential model; it becomes linear after taking logs of the target, but that changes the loss being minimised.
  • d — Linear. Fittable by OLS with the features [1, x₁, x₁x₂]. The product is a new feature, constructed from two originals.
  • e — Linear. Fittable by OLS with the features [1, x₁, x₂, x₁²x₂]. Complicated feature, simple model.
  • f — Not linear. The coefficient on x² is w₁², a nonlinear function of the parameter. Two different values of w₁ (w₁ and −w₁) give the same model, and the least-squares problem has no unique solution. Not fittable by OLS as written.

Exercise 4 — Effect of rescaling

A model predicting energy consumption (in kWh) is:

ŷ = 0.85 · temperature_C + 3.20 · occupancy − 12.5

Answer the following without fitting anything:

  1. Convert the temperature feature to Fahrenheit. Write the new model. What are the three new coefficients?
  2. Verify that a prediction for 20 °C with occupancy 4 is the same under both models.
  3. Now suppose the target is converted from kWh to watt-hours (multiply by 1,000). Write the new model.
  4. If you standardise temperature — subtract the mean of 15 °C and divide by a standard deviation of 6 °C — what happens to the intercept? Can you compute it without knowing the mean of the target?
Show answers

1. The transformation is xF = 1.8xC + 32, so xC = (xF − 32)/1.8. Substituting:

ŷ = 0.85 · (x_F − 32)/1.8 + 3.20 · occupancy − 12.5
  = (0.85/1.8) · x_F − (0.85·32)/1.8 + 3.20 · occupancy − 12.5
  = 0.4722 · x_F + 3.20 · occupancy − 27.61

New coefficients: temperature 0.4722 (kWh per °F), occupancy 3.20 (unchanged, since that feature was not rescaled), intercept −27.61.

2. 20 °C = 1.8(20) + 32 = 68 °F.

Celsius model   : 0.85(20) + 3.20(4) − 12.5
                = 17.0 + 12.8 − 12.5  =  17.3 kWh

Fahrenheit model: 0.4722(68) + 3.20(4) − 27.61
                = 32.11 + 12.8 − 27.61  =  17.3 kWh   ✓

3. Every coefficient multiplies by 1,000, including the intercept:

ŷ = 850 · temperature_C + 3200 · occupancy − 12500    (watt-hours)

4. Standardising a feature shifts the intercept to absorb the offset. With x′ = (x − 15)/6, substituting gives ŷ = 0.85(6x′ + 15) + 3.20 · occupancy − 12.5 = 5.1x′ + 3.20 · occupancy + 0.25. The new intercept is +0.25, and it can be computed without knowing the mean of the target — it follows purely from the substitution. It now represents the prediction for a day at the average temperature (15 °C) with zero occupancy, which is a far more meaningful baseline than 0 °C.

Exercise 5 — Reasoning about behaviour

A fitted model has coefficients w₁ = +3, w₂ = −5 and b = +20. Without Computing anything, describe what happens to the prediction in each case, and explain why.

  1. x₁ increases by 4.
  2. x₂ increases by 4.
  3. Both features increase by 4 simultaneously.
  4. Every feature is multiplied by 2, and the bias is unchanged.
  5. Both features are shifted by +10, and the bias is unchanged.
  6. The model is refitted with the constraint b = 0.
Show answers
  1. +12. Each unit increase in x₁ adds 3, so four units add 12.
  2. −20. Each unit increase in x₂ subtracts 5, so four units subtract 20.
  3. −8. The two effects add: +12 − 20 = −8. Because the model is additive, the total effect of simultaneous changes is the sum of the individual effects.
  4. Doubles the weighted part, leaves the bias alone. The prediction becomes 2(w₁x₁ + w₂x₂) + 20 rather than w₁x₁ + w₂x₂ + 20. The change to the prediction depends on the original values; it is not a simple doubling unless the bias is also doubled.
  5. Increases by 10(w₁ + w₂) = 10(3 − 5) = −20. Shifting both features by the same amount changes the prediction by the sum of the coefficients times the shift. Note that the model's slope is unchanged — only the level shifts.
  6. The fit gets worse. Removing the intercept constrains the model to pass through the origin, and the current intercept of +20 is clearly doing useful work. The optimal coefficients on the features will change to compensate, and the residual sum of squares can only increase. A constraint can never improve the best achievable fit on the training data.

9 Problem set

These problems are longer and more open-ended. They feed directly into Assignment 2.

Problem 1 — Write down the model before you fit it

Choose a regression dataset from a domain you know something about. Two options:

Before fitting anything, write a one-page specification containing:

  1. The target, in units.
  2. A list of features you intend to use.
  3. For each feature, your predicted sign of the coefficient, and a one-sentence reason based on domain knowledge.
  4. Your predicted relative magnitudes — which features do you expect to matter most, and why?
  5. Any feature you expect to be non-linear, and how you would handle it.

Then fit the model and compare the actual coefficients against your predictions.

The point of this exercise is not to be right. It is to discover which of your assumptions about the domain were wrong, because those are the places where the data has something to teach you. A coefficient whose sign contradicts your prediction is either a modelling error, a data problem, or a genuine surprise — and finding out which is real work.

Problem 2 — The cost of the intercept

This problem explores what the bias term buys you quantitatively.

  1. Take a real regression dataset and fit a model with an intercept.
  2. Compute the RSS, RMSE and R².
  3. Refit the same model with the intercept forced to zero (in scikit-learn, set fit_intercept=False). Compute the same three metrics.
  4. How much worse is the constrained model? Express the difference as a percentage.
  5. Plot the residuals for both models against the fitted values. What pattern appears in the constrained model?
  6. Now centre the target — subtract its mean — and refit without an intercept. Compare the coefficients against the original model. What do you notice about the feature coefficients?
  7. Write a paragraph explaining when, if ever, forcing the intercept to zero is the right thing to do.

Problem 3 — Engineer a feature, measure the effect

Choose a dataset with at least one feature you suspect has a non-linear relationship with the target. Then:

  1. Fit a plain linear model using only that feature. Record the RMSE and R².
  2. Plot the residuals against the feature. Describe the pattern.
  3. Add a squared term (x²) as an additional feature. Refit. How much did the RMSE improve?
  4. Plot the new residuals. Has the pattern gone?
  5. Add a cubic term (x³) as well. Does it improve further, or has the improvement flattened?
  6. Compute the training RMSE and a held-out validation RMSE for each of the three models. Does the model with the most features have the best validation performance?
  7. Write a short paragraph on where you would stop adding polynomial terms, and what evidence you would use to decide.

This problem is a first encounter with the bias–variance tradeoff, which Tutorial 7 treats in detail. You do not need to have a formal answer yet — the goal is to notice that training error and validation error behave differently as you add parameters.

Problem 4 — Where the linear model fails

This problem asks you to find a case where a linear model is genuinely inadequate, and to characterise the failure precisely.

  1. Find or construct a dataset with a relationship that is clearly non-linear — a sine wave, an exponential curve, or a step function would all work.
  2. Fit a linear model. Report the coefficients, the RMSE and the R². An R² of 0.7 on a sine wave is not a good model; explain why the number alone is misleading here.
  3. Plot the fitted line over the data. Where does the model perform worst?
  4. Plot the residuals against the feature. Describe the pattern in detail — is it periodic, monotonic, or something else?
  5. Now add polynomial features up to degree 5 and refit. Does the fit improve? Where does the polynomial model still struggle?
  6. For a step function, explain why no polynomial will ever fit well without using a very high degree, and what feature you would construct instead.
  7. Write a paragraph summarising the difference between a model that is wrong because its parameters are poorly chosen and one that is wrong because its functional form cannot represent the truth.

10 Discussion and projects

Discussion prompt — post 150–250 words

A coefficient is not a fact about the world. It is a fact about your data, given your model.

The same feature can have a positive coefficient in one study and a negative coefficient in another, even when both studies are correctly executed. This happens when the two studies control for different other variables, when they cover different populations, or when the feature is correlated with something neither study measured.

Find or recall an example — from the news, from your own field, or from a paper — where a regression coefficient was reported as if it were a causal fact about the world. Describe the coefficient, explain what it would take for the causal reading to be justified, and identify at least one plausible omitted variable that could reverse the sign of the effect.

Mini-project — coefficient stability check

Build a small experiment that tests how stable the coefficients of a linear model are.

  1. Choose a dataset with at least four features.
  2. Fit the model on the full dataset and record the coefficients.
  3. Now fit the model on 100 random 80% subsamples, holding all features fixed. Record the coefficients each time.
  4. Plot the distribution of each coefficient across the 100 fits. Which coefficients are stable, and which vary wildly?
  5. Now compute the correlation matrix of the features. Is there a relationship between the variability of a coefficient and the correlation of its feature with the others?
  6. Remove the most correlated feature and repeat the experiment. Does the remaining set of coefficients become more stable?
  7. Write a 200-word summary of what you found, and what it implies about how much confidence to place in a coefficient from a single fit.

This is a preview of a serious problem in applied statistics. When features are correlated, individual coefficients can be unstable even though the model's predictions are fine. The model is useful; the coefficients are not trustworthy individually. Recognising that distinction is a core professional skill.

Discussion prompt — the interpretability trade

The linear model's great advantage is that you can read its coefficients. This interpretability is bought at the cost of flexibility: the model cannot represent interactions or curvature unless you build them in by hand.

Describe a situation where you would trade some predictive accuracy for coefficient interpretability — for example, a regulatory context, a clinical setting, or a decision that has to be explained to a non-technical stakeholder. Then describe the opposite situation, where you would accept a black-box model because accuracy matters more than explanation. Be specific about the decision being made and who bears the cost of an error.

11 Summary

What you should take away

Key terms

Hypothesis function
The function h(x) that maps a feature vector to a prediction. For a linear model, h(x) = wᵀx + b.
Weight (coefficient, parameter)
The multiplier wj attached to feature j. Measures the change in the prediction per unit change in that feature, holding all others fixed.
Bias (intercept, offset)
The constant b added to the weighted sum. The prediction when every feature is zero.
Weight vector (w)
The vector containing all the weights, including the bias when the design matrix is augmented.
Dot product (wᵀx)
The sum of element-wise products of two vectors. The core arithmetic operation of a linear model.
Design matrix (X)
The n × (d+1) matrix whose rows are the feature vectors, with a leading column of ones for the bias.
Augmented feature vector
A feature vector with a leading 1 prepended, so that the bias can be treated as just another weight.
Hyperplane
A flat surface in more than three dimensions. The set of predictions a linear model can make.
Linear in the parameters
A property of a model in which the parameters enter only as multiplicative constants and additive terms — no parameter appears inside a function or raised to a power.
Partial effect
The change in the prediction per unit change in one feature, holding all other features constant. The interpretation of a coefficient in a multiple regression.
Interaction
A situation in which the effect of one feature depends on the value of another. Represented in a linear model by adding the product of the two features as a new feature.
Extrapolation
Making predictions outside the range of feature values observed in training. Unreliable for any model, and especially so for a linear one.
Omitted-variable bias
The distortion of a coefficient that occurs when a relevant feature is left out of the model and is correlated with an included one.

You are ready for Tutorial 3 when…

12 Further reading

James, Witten, Hastie & Tibshirani — An Introduction to Statistical Learning, §3.1–3.2 free online Sections 3.1 and 3.2 develop simple and multiple linear regression with the same notation used here, and Section 3.3 covers interaction terms and polynomial features in more detail. The discussion of the standard errors on the coefficients goes beyond this course but is worth skimming for context.
Deisenroth, Faisal & Ong — Mathematics for Machine Learning, ch. 3 and 5 free online Chapter 3 covers the linear algebra of vectors and matrices, including dot products and matrix multiplication. Chapter 5 covers vector calculus. If the matrix form ŷ = Xw feels opaque, Chapter 3 is the background you are missing.
Hastie, Tibshirani & Friedman — The Elements of Statistical Learning, §3.2 free online A more formal treatment of linear regression, including the geometry of the design matrix and the conditions under which the least-squares solution exists. Section 3.2.2 discusses the rank of X and what happens when it is deficient.
Gelman & Hill — Data Analysis Using Regression and Multilevel/Hierarchical Models, ch. 3–4 textbook An excellent treatment of how to interpret regression coefficients in applied settings, including centring, scaling and the interpretation of interactions. More focused on practice and interpretation than on theory, which is exactly what this tutorial is about.
scikit-learn — Linear Models user guide reference The LinearRegression documentation, including the fit_intercept parameter and its effect. The examples showing how the design matrix is constructed internally are a useful complement to Section 3.6.
Box — "Science and Statistics" (1976) classic The source of the famous line that all models are wrong but some are useful. A short, readable essay on why model choice is always a compromise, and why the linear model remains valuable despite its limitations. Worth reading alongside the limitations section of this tutorial.
Fox — Applied Regression Analysis and Generalized Linear Models, ch. 4–5 textbook A thorough treatment of the interpretation of multiple regression coefficients, including a detailed discussion of partial effects and the conditions under which they can be read causally. Chapter 5 covers the design matrix in detail.

What to read next

If you read one thing from this list before Tutorial 3, read Section 3.2 of An Introduction to Statistical Learning. It covers the same ground as this tutorial — the hypothesis function, the coefficients, the design matrix — with a slightly different emphasis, and it introduces the standard errors that tell you how much confidence to place in each coefficient. That material is beyond this course's scope, but knowing it exists will help you read applied work critically.

👤