0. The goal in plain words

The College data set has information on 777 US colleges (one row = one college). We want to predict Apps, the number of applications a college receives, using the other 17 variables (for example Accept, Enroll, Outstate, Expend, Private).

We try five methods and compare them by their test error:

# Method Main idea
1 Least squares (OLS) Normal linear regression, no penalty
2 Ridge OLS + penalty that shrinks all coefficients toward 0
3 Lasso OLS + penalty that can shrink some coefficients exactly to 0
4 PCR Make new variables (components) from the predictors, then regress on the first M
5 PLS Same as PCR, but the components are built to be useful for predicting Apps

Test error used here: the test MSE = average of (actual − predicted)² on colleges the model never saw. Smaller is better. I also report RMSE (= √MSE, in “number of applications”, easier to read) and test R².

A quick look at the data

dim(College)
## [1] 777  18
head(College[, c("Private", "Apps", "Accept", "Enroll", "Outstate", "Expend")])
summary(College$Apps)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##      81     776    1558    3002    3624   48094
sum(is.na(College))
## [1] 0

How to read this:

  • dim shows 777 rows and 18 columns (1 response + 17 predictors).
  • Apps ranges from very small to very large colleges and is right-skewed (the mean is higher than the median). This is why the errors will look big in absolute numbers.
  • There are no missing values, so we do not need to clean anything.
  • Private is a Yes/No (factor) variable. R automatically turns it into a 0/1 dummy (PrivateYes).

(a) Split the data into training and test sets

Why? If we test a model on the same data it learned from, the error looks too good. So we hide 30% of the colleges (the test set), train on the other 70%, then measure the error on the hidden 30%.

set.seed(1)                       # makes the random split reproducible
n     <- nrow(College)
train <- sample(n, round(0.7 * n))   # 70% of rows (544) for training
tr    <- College[train, ]         # training data
te    <- College[-train, ]        # test data (all other rows)

c(training = nrow(tr), test = nrow(te))
## training     test 
##      544      233
# helper: test MSE for any vector of predictions
test_mse <- function(pred) mean((te$Apps - pred)^2)

# ridge/lasso need a numeric matrix (model.matrix makes Private -> PrivateYes)
x <- model.matrix(Apps ~ ., data = College)[, -1]   # [, -1] removes the intercept column
y <- College$Apps

Explanation:

  • set.seed(1) fixes the random numbers, so everyone gets the same split and the same results.
  • sample(n, round(0.7 * n)) picks 544 random colleges (70%) for training. The remaining 233 (30%) are the test set.
  • Why 70/30? With only 777 colleges, we want enough training data to fit the models well, while keeping a test set that is still large enough to measure the error.
  • The same split is used for all 5 models, so the comparison is fair.
  • The test set is never used to choose λ or M. We only use it at the end to measure the error.

(b) Least squares linear regression

ols_fit  <- lm(Apps ~ ., data = tr)
ols_pred <- predict(ols_fit, newdata = te)
mse_ols  <- test_mse(ols_pred)

c(test_MSE = mse_ols, test_RMSE = sqrt(mse_ols))
##    test_MSE   test_RMSE 
## 1266406.906    1125.347

Explanation: lm(Apps ~ ., data = tr) uses all other variables as predictors. We then predict the test colleges and compute the MSE. OLS test MSE = 1,266,407, so a typical prediction is off by about 1125 applications.

Which predictors matter in OLS? (only the significant ones, p < 0.05)

cf <- summary(ols_fit)$coefficients
round(cf[cf[, 4] < 0.05, ], 4)
##             Estimate Std. Error t value Pr(>|t|)
## PrivateYes -509.5983   164.3172 -3.1013   0.0020
## Accept        1.7214     0.0476 36.2008   0.0000
## Enroll       -1.0418     0.2419 -4.3077   0.0000
## Top10perc    53.5355     6.4346  8.3200   0.0000
## Top25perc   -16.1699     5.0878 -3.1782   0.0016
## Outstate     -0.0878     0.0217 -4.0469   0.0001
## Room.Board    0.1623     0.0557  2.9139   0.0037
## Expend        0.0598     0.0134  4.4757   0.0000
## Grad.Rate     7.1602     3.5172  2.0358   0.0423
cat("Training R-squared:", round(summary(ols_fit)$r.squared, 3), "\n")
## Training R-squared: 0.933

How to read this: The most important predictor is Accept (number of applications accepted): every extra accepted student goes with about 1.72 more applications, with a huge t-value. Other significant variables include PrivateYes (private colleges get fewer applications, other things equal), Enroll, Top10perc, Top25perc, Outstate, Room.Board, Expend, and Grad.Rate. The training R² is high, so the linear model already explains most of the variation.

(c) Ridge regression

Idea: Ridge minimizes RSS + λ × Σβ². A bigger λ shrinks coefficients more. This helps when predictors are correlated (here Accept, Enroll, F.Undergrad are strongly related), because it makes the estimates more stable.

Choosing λ: cv.glmnet tries many values of λ and uses 10-fold cross-validation on the training set. We pick lambda.min, the λ with the lowest CV error.

set.seed(1)
cv_ridge <- cv.glmnet(x[train, ], y[train], alpha = 0)   # alpha = 0 -> ridge
plot(cv_ridge)

best_lambda_ridge <- cv_ridge$lambda.min
best_lambda_ridge
## [1] 367.2207
ridge_pred <- predict(cv_ridge, s = best_lambda_ridge, newx = x[-train, ])
mse_ridge  <- test_mse(ridge_pred)
c(test_MSE = mse_ridge, test_RMSE = sqrt(mse_ridge))
##    test_MSE   test_RMSE 
## 1125663.772    1060.973

How to read the plot:

  • The x-axis is log(λ), the y-axis is the CV error (MSE). The red dots are the CV error, and the grey bars show its uncertainty.
  • The left dashed line is lambda.min (lowest error). The right dashed line is lambda.1se (the simplest model within 1 standard error).
  • Our chosen λ = 367. Ridge λ is on a different scale from lasso λ, so do not compare them directly. Here the penalty is strong enough to clearly shrink the coefficients (see the coefficient table in part (d)).

Result: Ridge test MSE = 1,125,664 (OLS was 1,266,407). Ridge is 11.1% lower than OLS. Shrinking the correlated predictors (Accept, Enroll, F.Undergrad) makes the estimates more stable, which helps on new data.

(d) Lasso

Idea: Lasso minimizes RSS + λ × Σ|β|. Unlike ridge, it can set some coefficients exactly to 0, so it also does variable selection.

set.seed(1)
cv_lasso <- cv.glmnet(x[train, ], y[train], alpha = 1)   # alpha = 1 -> lasso
plot(cv_lasso)

best_lambda_lasso <- cv_lasso$lambda.min
best_lambda_lasso
## [1] 1.959746
lasso_pred <- predict(cv_lasso, s = best_lambda_lasso, newx = x[-train, ])
mse_lasso  <- test_mse(lasso_pred)

lasso_coef <- coef(cv_lasso, s = best_lambda_lasso)
n_nonzero  <- sum(lasso_coef[-1] != 0)       # [-1] ignores the intercept

c(test_MSE = mse_lasso, test_RMSE = sqrt(mse_lasso), nonzero_coefficients = n_nonzero)
##             test_MSE            test_RMSE nonzero_coefficients 
##          1259544.346             1122.294               16.000

How to read the plot: The numbers along the top show how many predictors are still in the model at each λ. As λ grows, predictors drop out one by one.

Result: Lasso test MSE = 1,259,544, with 16 non-zero coefficients (out of 17 predictors). So at the CV-best λ the lasso keeps most predictors. This means few variables are useless here, so lasso behaves like OLS with a very small shrinkage (its λ is only 1.96).

For comparison, a simpler lasso using lambda.1se:

lasso_pred_1se <- predict(cv_lasso, s = cv_lasso$lambda.1se, newx = x[-train, ])
c(test_MSE = test_mse(lasso_pred_1se),
  nonzero  = sum(coef(cv_lasso, s = cv_lasso$lambda.1se)[-1] != 0))
## test_MSE  nonzero 
##  1320249        3

A larger λ removes more predictors, so the model is simpler, but the test error is usually a bit higher.

Which predictors did the lasso set to zero (if any)?

coef_table <- data.frame(
  OLS   = coef(ols_fit)[-1],
  Ridge = as.numeric(coef(cv_ridge, s = best_lambda_ridge))[-1],
  Lasso = as.numeric(lasso_coef)[-1]
)
round(coef_table, 3)

How to read this: Compare the three columns.

  • Lasso is almost the same as OLS (tiny λ, so very little shrinkage and no variable removed).
  • Ridge is clearly different. Its coefficients are pulled toward 0, and some correlated variables change a lot. For example Accept goes from about 1.7 (OLS) to about 1.1, and Enroll even changes sign. This is normal for ridge when predictors are strongly correlated.
  • A 0 in the Lasso column means the variable was removed. Removed here: Personal.

(e) Principal Component Regression (PCR)

Idea: PCA combines the correlated predictors into a few uncorrelated components, ordered by how much variation of the predictors they capture. PCR then regresses Apps on the first M components. scale = TRUE standardizes the variables first. This is important because Expend (thousands) and Grad.Rate (0–100) have very different scales.

set.seed(1)
pcr_fit <- pcr(Apps ~ ., data = tr, scale = TRUE, validation = "CV")
validationplot(pcr_fit, val.type = "MSEP", main = "PCR: CV error vs number of components")

M_pcr <- which.min(pcr_fit$validation$PRESS)   # M with the lowest CV error
M_pcr
## [1] 17
pcr_pred <- predict(pcr_fit, newdata = te, ncomp = M_pcr)
mse_pcr  <- test_mse(pcr_pred)
c(M = M_pcr, test_MSE = mse_pcr, test_RMSE = sqrt(mse_pcr))
##           M    test_MSE   test_RMSE 
##      17.000 1266406.906    1125.347

How to read the plot: The CV error stays high for most values of M and only falls to its lowest level when (almost) all components are used.

cv_rmse_pcr <- sqrt(pcr_fit$validation$PRESS / nrow(tr))
data.frame(M = c(1, 2, 5, 10, 15, 17), CV_RMSE = round(cv_rmse_pcr[c(1, 2, 5, 10, 15, 17)]))

Result: CV chooses M = 17. With M = 17 (all components) PCR is identical to OLS (same fit, same test MSE = 1,266,407). So for this data PCR gives no dimension reduction and no improvement (the CV RMSE only drops sharply at M = 16–17). The reason: the components with the most predictor variance are not always the ones best at predicting Apps.

(f) Partial Least Squares (PLS)

Idea: Like PCR, but PLS builds the components using Apps as well, so the first components are directly useful for prediction. That is why PLS usually needs fewer components than PCR.

set.seed(1)
pls_fit <- plsr(Apps ~ ., data = tr, scale = TRUE, validation = "CV")
validationplot(pls_fit, val.type = "MSEP", main = "PLS: CV error vs number of components")

M_pls <- which.min(pls_fit$validation$PRESS)
M_pls
## [1] 17
pls_pred <- predict(pls_fit, newdata = te, ncomp = M_pls)
mse_pls  <- test_mse(pls_pred)
c(M = M_pls, test_MSE = mse_pls, test_RMSE = sqrt(mse_pls))
##           M    test_MSE   test_RMSE 
##      17.000 1266406.906    1125.347

How to read the plot: PLS reaches a low CV error much earlier than PCR. The curve flattens after about M = 6 (CV RMSE about 1,170, compared with about 1,150 at M = 17). The strict minimum is at M = 17, but it is only slightly better than M = 6–8, so a smaller M (about 6) is a fair, simpler choice.

How much do we lose with fewer components?

small_M <- data.frame(
  M = c(2, 4, 6, 8, M_pls),
  PLS_test_MSE = sapply(c(2, 4, 6, 8, M_pls),
                        function(m) test_mse(predict(pls_fit, te, ncomp = m))),
  PCR_test_MSE = sapply(c(2, 4, 6, 8, M_pls),
                        function(m) test_mse(predict(pcr_fit, te, ncomp = m)))
)
small_M[, 2:3] <- round(small_M[, 2:3])
small_M

How to read this: For small M, PLS has a much lower test error than PCR (for example at M = 6). This is exactly the advantage of PLS: it finds components that are relevant to the response. When M grows to 17, both reach the OLS error. PLS with M = 4–8 is only slightly worse than the full model on the test set. (We never choose M from the test set; CV chose it.)

(g) Compare all methods and comment

results <- data.frame(
  Method    = c("OLS", "Ridge", "Lasso", "PCR", "PLS"),
  Setting   = c("-",
                paste0("lambda = ", signif(best_lambda_ridge, 3)),
                paste0("lambda = ", signif(best_lambda_lasso, 3), " (", n_nonzero, " non-zero)"),
                paste0("M = ", M_pcr),
                paste0("M = ", M_pls)),
  Test_MSE  = c(mse_ols, mse_ridge, mse_lasso, mse_pcr, mse_pls)
)
results$Test_RMSE <- sqrt(results$Test_MSE)
total_var <- mean((te$Apps - mean(tr$Apps))^2)           # error of the "predict the mean" model
results$Test_R2   <- 1 - results$Test_MSE / total_var

knitr::kable(results, digits = c(0, 0, 0, 0, 3), format.args = list(big.mark = ","))
Method Setting Test_MSE Test_RMSE Test_R2
OLS - 1,266,407 1,125 0.914
Ridge lambda = 367 1,125,664 1,061 0.923
Lasso lambda = 1.96 (16 non-zero) 1,259,544 1,122 0.914
PCR M = 17 1,266,407 1,125 0.914
PLS M = 17 1,266,407 1,125 0.914
barplot(results$Test_RMSE, names.arg = results$Method, col = "steelblue",
        ylab = "Test RMSE (applications)", main = "Test error by method")

plot(te$Apps, ridge_pred, xlab = "Actual Apps", ylab = "Predicted Apps (Ridge)",
     main = "Ridge: predicted vs actual on the test set", pch = 19, col = rgb(0, 0, 1, 0.4))
abline(0, 1, col = "red", lwd = 2)       # perfect prediction line

Comments

1. How accurately can Apps be predicted? Very well. The best test R² is about 0.92, which means the models explain about 92% of the variation in applications on unseen colleges. The typical error (RMSE) is about 1061 applications. This looks large, but Apps has a wide range (from 81 to over 48,000), so relative to the spread it is a good result. On the last plot, the points follow the red line closely. Some very large colleges are the hardest to predict.

2. Are there big differences among the five methods? Not really, except for ridge. OLS, lasso, PCR and PLS have (almost) the same test error (OLS = PCR = PLS = 1,266,407, lasso = 1,259,544). Ridge is the best, with 1,125,664, which is about 11.1% lower than OLS (RMSE 1061 vs 1125). This is an improvement, but a modest one given that all models already explain over 90% of the variation.

3. Why are the differences small, and why does ridge win?

  • We have 544 training rows but only 17 predictors, so OLS does not overfit much. There is little variance left for shrinkage to remove.
  • Lasso keeps 16 of 17 predictors, so almost no variable is useless (selection does not help).
  • PCR and PLS choose 17 and 17 components. With all components they equal OLS.
  • Ridge wins because several predictors are highly correlated (Accept, Enroll, F.Undergrad, Top10perc, Top25perc). Ridge shrinks these correlated coefficients together and gives more stable predictions, while lasso and OLS do not.

4. What would I recommend? For accuracy, use ridge (lowest test error). If a simpler model is preferred, PLS with about 6 components gives CV error close to the full model with far fewer inputs. Accept (accepted students) is the strongest predictor in the OLS and lasso models.

5. Limits of this result. The exact numbers depend on the random split (set.seed(1)). A different split would change the errors a little. The ranking can change too when methods are this close, so a repeated split or k-fold CV would give a more reliable comparison.

Appendix: session information

sessionInfo()
## R version 4.5.2 (2025-10-31 ucrt)
## Platform: x86_64-w64-mingw32/x64
## Running under: Windows 11 x64 (build 26200)
## 
## Matrix products: default
##   LAPACK version 3.12.1
## 
## locale:
## [1] LC_COLLATE=English_United States.utf8 
## [2] LC_CTYPE=English_United States.utf8   
## [3] LC_MONETARY=English_United States.utf8
## [4] LC_NUMERIC=C                          
## [5] LC_TIME=English_United States.utf8    
## 
## time zone: Asia/Bangkok
## tzcode source: internal
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] pls_2.9-0    glmnet_5.2   Matrix_1.7-4 ISLR2_1.3-2 
## 
## loaded via a namespace (and not attached):
##  [1] vctrs_0.7.0       cli_3.6.5         knitr_1.51        rlang_1.1.7      
##  [5] xfun_0.56         jsonlite_2.0.0    htmltools_0.5.9   sass_0.4.10      
##  [9] rmarkdown_2.30    grid_4.5.2        evaluate_1.0.5    jquerylib_0.1.4  
## [13] fastmap_1.2.0     yaml_2.3.12       foreach_1.5.2     lifecycle_1.0.5  
## [17] compiler_4.5.2    codetools_0.2-20  Rcpp_1.1.2        rstudioapi_0.18.0
## [21] lattice_0.22-7    digest_0.6.39     R6_2.6.1          splines_4.5.2    
## [25] shape_1.4.6.1     bslib_0.9.0       tools_4.5.2       iterators_1.0.14 
## [29] survival_3.8-3    cachem_1.1.0