Linear Regression
in Matrix Form
Understand how ordinary least squares becomes an elegant matrix equation, and why the solution is a geometric projection onto the column space of \(\mathbf{X}\).
Why Write Regression in Matrix Form?
In a typical regression course you see equations with summation symbols: \(\sum x_i y_i\), \(\sum x_i^2\), and so on. As the number of predictors grows, these sums become unwieldy. Matrices let us express everything in one compact equation.
Setting Up the Matrix Equation
We have \(n\) observations and \(p\) predictors. Stack everything into matrices:
Inside the Design Matrix \(\mathbf{X}\)
The Least Squares Objective
We want to choose \(\boldsymbol{\beta}\) to minimize the sum of squared residuals. In matrix notation this is a single expression:
Deriving the Normal Equations
The OLS Estimator
If \(\mathbf{X}^\top\mathbf{X}\) is invertible (columns of \(\mathbf{X}\) are linearly independent), we can solve directly:
Projection Geometry
The Hat Matrix \(\mathbf{H}\)
The fitted values are a linear function of \(\mathbf{y}\). The matrix that performs this projection is called the hat matrix:
Key Property: Orthogonality
The normal equations \(\mathbf{X}^\top\mathbf{X}\hat{\boldsymbol{\beta}} = \mathbf{X}^\top\mathbf{y}\) can be rewritten as:
Scalar vs Matrix Notation
| Scalar (summation) | Matrix | |
|---|---|---|
| Model | \(y_i = \beta_0 + \beta_1 x_i + \varepsilon_i\) | \(\mathbf{y} = \mathbf{X}\boldsymbol{\beta} + \boldsymbol{\varepsilon}\) |
| Objective | \(\sum_{i=1}^n (y_i - \hat{y}_i)^2\) | \(\|\mathbf{y} - \mathbf{X}\boldsymbol{\beta}\|^2\) |
| Solution | \(\hat{\beta}_1 = \frac{\sum x_i y_i - n\bar{x}\bar{y}}{\sum x_i^2 - n\bar{x}^2}\) | \((\mathbf{X}^\top\mathbf{X})^{-1}\mathbf{X}^\top\mathbf{y}\) |
| Fitted values | \(\hat{y}_i = \hat{\beta}_0 + \hat{\beta}_1 x_i\) | \(\hat{\mathbf{y}} = \mathbf{H}\mathbf{y}\) |
| Scales to \(p\) predictors? | Messy | Identical formula |
How to Apply the Formula
Example 1: Simple Regression
Data: \((1,2),\; (2,3),\; (3,5)\). Find \(\hat{\boldsymbol{\beta}}\).
Example 2: Verify Orthogonality
Continuing from Example 1: compute the residuals and check \(\mathbf{X}^\top\mathbf{e} = \mathbf{0}\).
Example 3: Multiple Regression
With two predictors \(x_1, x_2\) and 4 observations, the same recipe applies. The design matrix is \(4 \times 3\):
Common Mistakes
Question 1 of 5
If \(\mathbf{X}\) is an \(n \times (p+1)\) matrix, what are the dimensions of \(\mathbf{X}^\top\mathbf{X}\)?
Question 2 of 5
Which property does the hat matrix \(\mathbf{H}\) not possess?
Question 3 of 5
The equation \(\mathbf{X}^\top\mathbf{e} = \mathbf{0}\) tells us that:
Question 4 of 5
In the projection diagram, \(\hat{\mathbf{y}}\) is:
Question 5 of 5
Given \(\mathbf{X}^\top\mathbf{X} = \begin{bmatrix}3&6\\6&14\end{bmatrix}\) and \(\mathbf{X}^\top\mathbf{y} = \begin{bmatrix}10\\23\end{bmatrix}\), what is \(\hat\beta_1\) (the slope)?