Sub topic 2
The linear model and least squares
This chapter explains what a linear regression model computes and how ordinary least squares (OLS) picks its coefficients. It assumes you know basic Python, NumPy array shapes, and high-school algebra (the equation of a line, mean, variance). You do not need scikit-learn yet. All code here uses NumPy only, so you can see the mechanism before the library hides it.
The model: y = Xw + b
A linear regression model predicts a number as a weighted sum of input features plus a constant. For one sample with features x1, x2, ..., xp, the prediction is:
ŷ = w1·x1 + w2·x2 + ... + wp·xp + b
- Each weight (also called a coefficient) w_j says how much the prediction changes when feature j increases by one unit and the other features stay fixed.
- The intercept b is the prediction when every feature is zero.
- The hat on ŷ marks a prediction, to distinguish it from the true target y.
For all n samples at once, stack the features into a matrix X of shape (n, p) and the weights into a vector w of shape (p,). Then the predictions are:
ŷ = Xw + b
This is the same shape convention scikit-learn uses: rows are samples, columns are features.
The word "linear" refers to the model being linear in the weights, not necessarily in the raw inputs. A model with the features x and x² is still a linear model, because the prediction is a weighted sum of those columns. A later chapter uses this idea for curved relationships.
Residuals and the squared-error loss
No line passes through every noisy point, so we need a rule for which line is best. First define the residual for sample i as the actual value minus the predicted value:
ri = yi − ŷ_i
A positive residual means the model under-predicted. A negative one means it over-predicted.
We cannot just add the residuals, because positive and negative ones cancel. OLS squares each residual and sums them. This quantity is the residual sum of squares (RSS):
RSS(w, b) = Σ (yi − ŷi)²
Squaring has three effects:
- Errors never cancel each other.
- Large errors are punished much more than small ones. A miss of 10 costs 100, while ten misses of 1 cost 10 in total.
- The loss is smooth, so it has a clean mathematical minimum.
Ordinary least squares chooses the w and b that make RSS as small as possible on the training data.
Solving for the coefficients
For simple regression (one feature), the minimum has a closed form:
- slope w = cov(x, y) / var(x)
- intercept b = mean(y) − w · mean(x)
The slope is the covariance of x and y divided by the variance of x. The intercept then forces the line through the point (mean(x), mean(y)).
For many features, the same idea is written with matrices. Append a column of ones to X so that b becomes one more weight. Setting the gradient of RSS to zero gives the normal equations:
XᵀX · w = Xᵀy
When XᵀX is invertible, the solution is w = (XᵀX)⁻¹ Xᵀy. In practice, libraries avoid forming the inverse. They use a numerically safer routine such as a QR decomposition or the singular value decomposition (SVD). scikit-learn's LinearRegression uses SciPy's least-squares solver (scipy.linalg.lstsq), which is SVD-based.
The following code computes the coefficients three ways on the same data and shows that they agree.
import numpy as np
rng = np.random.default_rng(0)
n = 200
X = rng.uniform(0, 10, size=(n, 2))
true_w = np.array([3.0, -1.5])
true_b = 2.0
y = X @ true_w + true_b + rng.normal(0, 1.0, size=n)
# Add a column of ones so the intercept is learned as one more weight.
X1 = np.column_stack([X, np.ones(n)])
# 1. Normal equations, solved as a linear system (no explicit inverse).
beta_normal = np.linalg.solve(X1.T @ X1, X1.T @ y)
# 2. Least-squares solver (SVD-based), the numerically safer route.
beta_lstsq, *_ = np.linalg.lstsq(X1, y, rcond=None)
# 3. Simple-regression formulas applied to the first feature only.
x = X[:, 0]
slope = np.cov(x, y, bias=True)[0, 1] / np.var(x)
intercept = y.mean() - slope * x.mean()
print("normal equations:", beta_normal)
print("lstsq: ", beta_lstsq)
print("one-feature slope, intercept:", slope, intercept)The first two lines print nearly identical numbers close to [3.0, -1.5, 2.0]. The one-feature result differs because it ignores the second feature. This is a reminder that a coefficient depends on which other features are in the model.
Why squared error: a geometric and a statistical view
Two views explain why OLS is the default.
Geometric view. The columns of X span a subspace. The vector of predictions Xw must lie in that subspace. OLS finds the point in the subspace closest to y, which is the orthogonal projection of y onto it. At the solution, the residual vector is perpendicular to every column of X.
Statistical view. If the noise is independent and normally distributed with constant variance, minimizing RSS gives the maximum-likelihood estimate of the weights. Even without normal noise, the Gauss-Markov theorem says OLS has the smallest variance among linear unbiased estimators, provided the noise has zero mean, constant variance, and no correlation between samples.
You can check the geometric claim directly.
import numpy as np
rng = np.random.default_rng(1)
X = rng.normal(size=(100, 3))
y = X @ np.array([1.0, 2.0, -1.0]) + 0.5 + rng.normal(0, 0.3, size=100)
X1 = np.column_stack([X, np.ones(100)])
beta, *_ = np.linalg.lstsq(X1, y, rcond=None)
residuals = y - X1 @ beta
print("sum of residuals:", residuals.sum())
print("X1.T @ residuals:", X1.T @ residuals)Both outputs are numerically zero, within floating-point error. The residuals sum to zero because of the intercept column, and they are uncorrelated with every feature because of the orthogonality at the OLS solution.
Edge cases and failure modes
OLS has a unique solution only under certain conditions. Know these before you meet them in practice.
| Situation | What happens | Typical fix |
|---|---|---|
| More features than samples (p > n) | Infinitely many exact fits, no unique solution | Regularization, fewer features, more data |
| Duplicate or perfectly dependent columns | XᵀX is singular, coefficients are not unique | Drop a column, or regularize |
| Strongly correlated columns | Solution exists but coefficients are unstable | Regularization, combine features |
| Features on very different scales | Solution is fine, but coefficients are hard to compare | Scale features |
| Outliers | Squared loss lets one extreme point pull the line | Inspect data, consider a robust loss |
| A curved true relationship | Line systematically misses | Add transformed features |
Three further points often cause confusion:
- Scaling does not change the fit. Multiplying a feature by 100 divides its weight by 100, and the predictions stay the same. Scaling matters for interpretation and, later, for regularized models.
- The intercept is not optional. Without it, the line is forced through the origin, which biases the fit when the data does not pass through zero. Always include it unless you have a reason not to.
- Extrapolation is risky. The line extends forever, but the real relationship may not. Predictions far outside the training range deserve suspicion.
Summary of the working model
- The model predicts ŷ = Xw + b, linear in the weights.
- The residual is y − ŷ. OLS minimizes the sum of squared residuals.
- The minimizer solves the normal equations, XᵀX · w = Xᵀy, which libraries solve with stable decompositions.
- The solution is unique only when the columns of X are linearly independent.
- The fit says nothing by itself about performance on new data.
Exercise
You fit OLS with an intercept and compute the residuals on the training data. (a) What should their sum be? (b) A teammate multiplies one feature column by 1000 and refits. What happens to that feature's coefficient and to the predictions?
Show answer
(a) The sum is zero, apart from floating-point error. The intercept column makes the residual vector orthogonal to a column of ones, and that is the same as summing to zero. (b) The coefficient becomes 1000 times smaller, because the feature is 1000 times larger and must contribute the same amount to the prediction. The predictions are unchanged, since OLS finds the same projection of y onto the same column space.
Exercise
A dataset has 50 samples and 80 features, and no regularization is used. Why is the OLS solution not unique, and does a perfect training fit say the model is good?
Show answer
With p > n, XᵀX is singular (its rank is at most 50), so many different weight vectors give the same predictions and can fit the training targets exactly. A perfect training fit says little. The model has enough freedom to reproduce noise, so it will usually predict new data poorly.