Why? The fitted value \(\hat{y}_i\) uses \(y_i\) with weight \(h_{ii}\)
When we remove \(y_i\), we need to account for its influence
Computing LOOCV in R
set.seed(1)n <-50x <-runif(n, 0, 10)y <- x +rnorm(n)model <-lm(y ~ x)# Get hat values (leverages)h <-hatvalues(model)# Get residualsresid <-residuals(model)# LOOCV using the shortcut formulacv_error <-mean((resid / (1- h))^2)cv_error
[1] 0.8909796
LOOCV for Model Selection
I generated data with a quadratic relationship and then fit increasingly flexible models.
Use cross-validation to find \(\lambda\) that minimizes prediction error!
LOOCV is a standard approach for selecting \(\lambda\)
Ridge Regression with CV
library(glmnet)# Use previous data# alpha = 0 means ridge (alpha = 1 would be lasso)ridge_cv <-cv.glmnet(X_scaled, y, alpha =0)# Plot CV errorplot(ridge_cv, main ="Cross-Validation for Ridge Regression")
LOOCV Shortcut for Ridge
Good news: The hat matrix trick works for ridge too!
For ridge regression with penalty \(\lambda\), the hat matrix is: