Machine Learning

Linear Regression — exercises

Recognize a problem as "fit a model that is linear in its parameters," set up the design matrix, solve XᵀXβ = Xᵀy by normal equations or QR, and read coefficient stability vs prediction stability from the conditioning of X.

1 worked example · 7 practice problems · 2 check problems

Worked example: fitting a line by hand

Problem. Fit by ordinary least squares to the five data points . Report , the residuals, and . Do it by hand, then check with code.

Diagnosis. Linear regression in one feature. Set up the design matrix with a column of ones for the intercept and for the feature, then solve the normal equations . For one feature the algebra simplifies to the textbook scalar formulas, but the matrix view will be what generalizes.

Predict before reading on: eyeball the data before doing any algebra. What slope do you expect, roughly? What intercept? You should be able to predict to within 0.1 just by looking.

Solution. Five sums:

For a single feature, the OLS estimator collapses to

Plug in:

Predict before reading on: these formulas drop out of when has exactly two columns (a ones column plus one feature). Convince yourself this is true — what entries of the matrix show up in the denominator of ?

Residuals. Predicted values give . Residuals are . They alternate sign and are small relative to — the model fits well.

R-squared. . . So . The model captures 99.7% of the variance.

Verification.

import numpy as np
x = np.array([1, 2, 3, 4, 5])
y = np.array([2.1, 3.8, 6.2, 7.9, 10.1])
X = np.column_stack([np.ones(5), x])
beta = np.linalg.solve(X.T @ X, X.T @ y)
print(beta)            # [-0.01  2.01]
y_hat = X @ beta
print(1 - np.sum((y - y_hat)**2) / np.sum((y - y.mean())**2))   # 0.9974

Articulate: state in one sentence what linear regression actually does — what objective it minimizes, and over what.


Practice problems

Seven problems, seven different surfaces. Each is the same move from the worked example — set up the design matrix, solve the normal equations, read the result. The features change, the trick doesn't.

P.1 climate trends, time-series fit

Annual temperature anomalies (°C) at one station for five consecutive years are:

year offset x = 0, 1, 2, 3, 4
anomaly    y = 0.50, 0.55, 0.62, 0.68, 0.75

Fit by hand. What's the implied warming rate per decade?

Find the analogue: same one-feature OLS as the worked example. Compute and plug into the scalar formula.

show answer

With : , , .

°C/year.

°C.

Warming rate: 0.63 °C/decade.

P.2 free-fall physics, nonlinear-in-t but linear-in-parameters

A ball dropped from a tower has its height measured at six times. The data:

t (s)  = 0.0, 0.2, 0.4, 0.6, 0.8, 1.0
h (m)  = 5.00, 4.81, 4.22, 3.24, 1.85, 0.12

Fit the model and extract . Notice the model is nonlinear in but linear in the parameters .

Find the analogue: "linear in parameters" is the key property. What feature column does multiply? Build the design matrix accordingly and use the same OLS solve.

show answer

Reparametrize as with and . The design matrix has columns , so .

Solving gives , .

So m and m/s² — within 0.2% of the textbook value.

P.3 polynomial curve fitting

Fit a quadratic to:

x = -2, -1,  0,  1,  2
y =  9.1, 4.05, 1.0, 0.05, 0.95

Report . The true generating polynomial (before noise was added) was .

Find the analogue: polynomial regression is linear regression in disguise. The design matrix gets one column per power of . Same solve, more columns.

show answer

Design matrix with columns :

X = [[1, -2, 4],
     [1, -1, 1],
     [1,  0, 0],
     [1,  1, 1],
     [1,  2, 4]]

Solving the normal equations gives , close to the true from .

The minor deviation is just the OLS estimator absorbing the noise. With noise-free data it would recover the true coefficients exactly.

P.4 economic elasticity, log-log regression

Engel's law says food expenditure grows sub-linearly with income. Given five households:

income (k$)  = 20,  40,  60,  80,  100
food   (k$)  = 5.0, 8.7, 11.7, 14.4, 16.7

Fit . Report , which is the elasticity — the percentage change in food per percentage change in income.

Find the analogue: the relationship is nonlinear in the raw variables but linear in their logs. Build a design matrix with as the feature column. Same OLS solve.

show answer

Let and . Compute , , , .

Plug into the one-feature formula: , .

Elasticity ≈ 0.75: a 1% increase in income produces about a 0.75% increase in food spending. Sub-unitary, just as Engel observed in 1857. Anything here is what makes food a "necessity good" in econ jargon.

P.5 sensor calibration with inverse application

A pressure transducer is calibrated against a reference. The (pressure, voltage) pairs are:

P (kPa)  =  0,   10,   20,   30,   40
V (V)    = 0.50, 1.45, 2.51, 3.49, 4.55

(a) Fit . (b) Use the fit to convert a future reading of V into kPa.

Find the analogue: part (a) is the worked example with renamed variables. Part (b) inverts the fit — same parameters, solve algebraically for in terms of .

show answer

(a) , , , . Plug in: V/kPa. V.

(b) Invert: . For : kPa.

This is how every calibration curve in a lab works — fit once, use the inverse forever.

P.6 numerical conditioning, multicollinearity diagnosis

Construct a 200-sample, 3-feature dataset where is a near-exact copy of (differ only at the 7th decimal place). Generate with small Gaussian noise. Compute . Solve the normal equations and report . Then solve via np.linalg.lstsq and compare. What's similar, what's different?

Find the analogue: the worked example assumed was well-conditioned. This problem is what happens when it isn't — and surfaces the difference between what the data can tell you (predictions) and what it cannot (individual coefficients).

show answer
import numpy as np

rng = np.random.default_rng(0)
n  = 200
x1 = rng.normal(0, 1, n)
x2 = rng.normal(0, 1, n)
x3 = x1 + x2 + rng.normal(0, 1e-7, n)   # x3 ≈ x1 + x2

X  = np.column_stack([np.ones(n), x1, x2, x3])
y  = 1.0 + 2.0 * x1 + 1.0 * x2 + rng.normal(0, 0.1, n)

print("cond(XᵀX) =", f"{np.linalg.cond(X.T @ X):.2e}")
print("β (normal eq):", np.linalg.solve(X.T @ X, X.T @ y))
print("β (lstsq)   :", np.linalg.lstsq(X, y, rcond=None)[0])
# Predictions, not coefficients, are what's stable.

, near double-precision limits. The two solvers give different coefficients for — the per-column splits are wildly unstable, often differing by factors of . But the predictions agree to between methods.

Reason: the data constrains linear combinations of that lie in the row-space of , not the individual coefficients. The null direction is essentially unconstrained, so any solver picks an arbitrary value there. The takeaway: when is large, look at predictions, not coefficients.

P.7 experimental design, weighted least squares

You're given data points with known but unequal noise levels . The standard OLS estimator treats every point equally; this overweights noisy points and underweights precise ones. Derive the weighted least-squares estimator that minimizes . Show your answer matches with .

Find the analogue: the derivation move is the same one that produced the OLS normal equations — set the gradient of the loss to zero. The only difference is the loss has weights.

show answer

Write the weighted loss as . Expand:

Gradient: .

Solving: . ✓

Equivalent recipe in practice: rescale each row of and by , then run plain OLS on the rescaled system. The rescaling makes the residuals equal-variance, which is what OLS optimality requires.

Aside: this is also the MLE under iid Gaussian noise with known per-point variance . Same algebra, different framing — the same answer drops out of the likelihood derivation.


Check problems

Two problems that resist pattern-matching against the practice set. Neither is solvable by remembering one of the problems above.

Check 1 articulation

The normal-equations route to OLS forms and solves . The QR route factors and solves . Mathematically they compute the same . Numerically, when , the normal-equations solver loses about 14 digits while the QR solver loses only 7.

In 150–250 words, explain why. Your explanation should distinguish what is being computed (the same minimizer) from how it is being computed (a different sequence of finite-precision operations). Make clear that the issue isn't the input data or the algorithm in isolation — it's their interaction. A reader who just finished the linear-regression page should be able to follow your explanation.

show solution sketch

The two routes converge to the same in exact arithmetic — that's what "mathematically the same" means. The difference shows up because finite-precision arithmetic amplifies errors at a rate that depends on the condition number of the matrices being inverted, and the two routes invert different matrices.

Forming squares the condition number: . The normal-equations solver then has to invert that squared-conditioned matrix, and forward error scales as condition number times machine epsilon. With and machine epsilon , the normal equations lose about digits.

QR factorization never forms . The Householder or Givens algorithm operates directly on , with arithmetic whose forward error scales as rather than its square. The loss is digits — half as many.

The issue isn't alone (any conditioning is fine if the operations are stable). It isn't the OLS formula alone (the minimizer is well-defined for any non-singular system). It's the realization: which intermediate matrices the algorithm forms and inverts in the working precision. Conditioning is a property of the realization, not the problem.

Check 2 derivation

Assume the linear model with iid Gaussian noise . Derive the covariance matrix of the OLS estimator:

Specialize to simple linear regression (single feature plus intercept) and use it to derive the closed-form standard error of the slope:

Discuss qualitatively: what makes small? What makes it large? Connect at least one factor to a practical experimental-design decision.

show solution sketch

General case. The OLS estimator is . Substitute :

So . Its covariance is

With , the middle three matrices collapse to , giving

Simple linear regression. With , .

The determinant is (using ). The inverse has -entry .

So , and . ✓

What controls it. Three things:

  • Noise level : smaller noise → smaller SE. Obvious.
  • Sample size : more data → larger sum → smaller SE. Standard scaling.
  • Spread of : data spread over a wide range gives much smaller SE than the same number of points clustered together. This is the experimental-design lever: when you can choose where to measure, spread the measurements out. Two points at the extremes of the design range are vastly more informative for the slope than ten points in a narrow cluster.

Practical implication: in a dose-response experiment, putting your samples at the extreme doses (rather than evenly spaced) maximizes the precision of the slope estimate, at the cost of nonlinearity diagnostics. Most experimental-design textbooks call this the "D-optimal" or "extreme-point" design.