Investigation: The ordinary least squares solution

Investigation: The ordinary least squares solution#

Ordinary least squares minimizes a sum of squared residuals. Its equivalence to maximum likelihood requires a specified error model, such as independent Gaussian errors of common variance. Existence of a numerical solution and validity of an inference are separate questions.

Question. Compare covariance-based coefficients, lm(), QR-based least squares, and numerical optimization for the same simulated data.

Before running: write the result you expect and what would challenge it. Data are simulated unless explicitly identified otherwise.

# Open this notebook from book/notebooks (or book/exercises).
course_path <- if (file.exists("../R/course.R")) "../R/course.R" else "book/R/course.R"
stopifnot(file.exists(course_path))
source(course_path)
set.seed(432)
d <- data.frame(x=rnorm(100))
d$y <- 3+2*d$x+rnorm(100,0,.7)
fit <- lm(y~x,d)
slope <- cov(d$x,d$y)/var(d$x)
intercept <- mean(d$y)-slope*mean(d$x)
X <- model.matrix(fit)
qr_estimate <- qr.solve(X,d$y)
objective <- function(beta) sum((d$y-drop(X%*%beta))^2)
numerical <- optim(c(0,0),objective,method="BFGS")$par
rbind(lm=coef(fit),covariance=c(intercept,slope),qr=qr_estimate,numerical=numerical)
stopifnot(max(abs(qr_estimate-coef(fit)))<1e-8,max(abs(numerical-coef(fit)))<1e-4)
A matrix: 4 × 2 of type dbl
(Intercept)x
lm3.0875981.909075
covariance3.0875981.909075
qr3.0875981.909075
numerical3.0875981.909075

Rank and numerical stability#

With full column rank, the normal equations identify a unique least-squares solution. QR or SVD avoids explicitly forming an inverse. With rank deficiency, fitted values can remain identifiable even when individual coefficients are not.

d$duplicate_x <- d$x
rank_deficient <- lm(y~x+duplicate_x,d)
coef(rank_deficient)
c(columns=ncol(model.matrix(rank_deficient)),rank=rank_deficient$rank)
stopifnot(rank_deficient$rank < ncol(model.matrix(rank_deficient)))
(Intercept)
3.08759797499017
x
1.90907537737818
duplicate_x
<NA>
columns
3
rank
2

The Gaussian assumption is used to connect this objective to a likelihood and conventional finite-sample inference; minimizing squared residuals itself does not require Gaussian observations. See the calculus refresher for derivatives and expectations.

Interpret and verify#

Check dimensions, agreement of predictions, and rank. Explain which assumptions are needed for estimation and which are needed for the chosen interval.

Failure to consider: Explicitly inverting a nearly singular cross-product matrix can be numerically unstable. Full column rank governs uniqueness; it is not the same as independent predictors.

Report the target, the numerical result with its units, the relevant uncertainty, and one limitation. Distinguish what is established by the simulation from what would require real data.

AI audit: critique the saved faulty claim in the companion exercise before using any live assistant. If you use AI, record the relevant suggestion, your independent check, and the final decision.

Translate the preceding linear model into an objective; use diagnostics to challenge that model next.

sessionInfo()
R version 4.2.1 (2022-06-23)
Platform: aarch64-apple-darwin20 (64-bit)
Running under: macOS 15.7.7

Matrix products: default
BLAS:   /Library/Frameworks/R.framework/Versions/4.2-arm64/Resources/lib/libRblas.0.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/4.2-arm64/Resources/lib/libRlapack.dylib

locale:
[1] C.UTF-8/C.UTF-8/C.UTF-8/C/C.UTF-8/C.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

loaded via a namespace (and not attached):
 [1] fansi_1.0.3         crayon_1.5.1        digest_0.6.29      
 [4] utf8_1.2.2          IRdisplay_1.1       repr_1.1.4         
 [7] lifecycle_1.0.1     jsonlite_1.8.0      evaluate_0.15      
[10] pillar_1.8.0        rlang_1.0.6         cli_3.3.0          
[13] uuid_1.1-0          vctrs_0.4.1         IRkernel_1.3.0.9000
[16] tools_4.2.1         glue_1.6.2          fastmap_1.1.0      
[19] compiler_4.2.1      base64enc_0.1-3     pbdZMQ_0.3-7       
[22] htmltools_0.5.3    

Attribution#

Notebook authored by Patience Stevens and edited by Amy Sentis and Fiona Horner.

Revised investigation: 2026 course revision. Original authorship is retained; examples and explanatory text have been updated.