Investigation: Statistical learning and the bias–variance tradeoff

Investigation: Statistical learning and the bias–variance tradeoff#

Expected prediction error depends on the data-generating process, training procedure, loss, and target population. Bias and variance describe behavior over repeated training samples. Parameter count alone is not a universal measure of effective complexity.

Question. Fit polynomial models to repeated noisy samples and compare squared bias, prediction variance, and noise on a fixed evaluation grid.

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)
truth <- function(x) sin(pi*x)
grid <- seq(-1,1,length.out=80)
degrees <- c(1,3,8)
B <- 150
noise_sd <- .25
predictions <- array(NA_real_,c(length(grid),B,length(degrees)))
for(b in seq_len(B)) {
  train <- data.frame(x=runif(45,-1,1))
  train$y <- truth(train$x)+rnorm(nrow(train),0,noise_sd)
  for(j in seq_along(degrees)) {
    fit <- lm(y~poly(x,degrees[j]),train)
    predictions[,b,j] <- predict(fit,data.frame(x=grid))
  }
}
metrics <- do.call(rbind,lapply(seq_along(degrees),function(j) {
  p <- predictions[,,j]
  c(degree=degrees[j],bias_squared=mean((rowMeans(p)-truth(grid))^2),variance=mean(apply(p,1,var)),noise=noise_sd^2)
}))
metrics <- as.data.frame(metrics)
metrics$expected_error_estimate <- with(metrics,bias_squared+variance+noise)
metrics
A data.frame: 3 × 5
degreebias_squaredvariancenoiseexpected_error_estimate
<dbl><dbl><dbl><dbl><dbl>
10.20552343620.0128570770.06250.28088051
30.00508287560.0077783510.06250.07536123
80.00035666130.0903842260.06250.15324089
matplot(metrics$degree,metrics[c("bias_squared","variance","expected_error_estimate")],type="b",pch=1:3,lty=1:3,col=c("black","blue","red"),xlab="Polynomial degree",ylab="Average squared error")
legend("topleft",c("Squared bias","Variance","Total with noise"),col=c("black","blue","red"),lty=1:3,pch=1:3)

Limits of the demonstration#

This is a finite Monte Carlo estimate over a fixed grid, not a universal law about parameter count. Repeat with larger samples or a shifted evaluation range. Regularization and interpolating models can have different complexity–error curves; report the observed behavior without changing seeds to force a preferred shape.

Interpret and verify#

Vary sample size and noise while keeping evaluation conditions fixed. Explain which parts of error change and why.

Failure to consider: A U-shaped curve is not guaranteed in every realized dataset or learning regime. Repeated simulation should estimate behavior rather than manufacture a desired curve.

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.

Use the information/knowledge distinction to motivate held-out prediction; linear models provide the first concrete estimator.

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