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².
\[\text{MSE} = \frac{1}{n}\sum_{i=1}^{n}\left(y_i - \hat{y}_i\right)^2 \qquad \text{RMSE} = \sqrt{\text{MSE}} \qquad R^2 = 1 - \frac{\text{MSE}}{\text{variance of } y}\]
Here \(y_i\) is the actual number of applications of college \(i\), \(\hat{y}_i\) is the predicted number, and \(n\) is the number of test colleges. \(R^2\) close to 1 means the predictions follow reality closely.
First, the size of the table and the names of all the columns:
dim(College) # rows and columns
## [1] 777 18
names(College) # all 18 column names: Apps + 17 predictors
## [1] "Private" "Apps" "Accept" "Enroll" "Top10perc"
## [6] "Top25perc" "F.Undergrad" "P.Undergrad" "Outstate" "Room.Board"
## [11] "Books" "Personal" "PhD" "Terminal" "S.F.Ratio"
## [16] "perc.alumni" "Expend" "Grad.Rate"
Here are all 17 predictors and the response, with their meaning:
| No | Variable | Meaning |
|---|---|---|
| Response | Apps | Number of applications received (the response) |
| 1 | Private | Private (Yes) or public (No) college |
| 2 | Accept | Number of applications accepted |
| 3 | Enroll | Number of new students enrolled |
| 4 | Top10perc | % of new students from the top 10% of their high school class |
| 5 | Top25perc | % of new students from the top 25% of their high school class |
| 6 | F.Undergrad | Number of full-time undergraduates |
| 7 | P.Undergrad | Number of part-time undergraduates |
| 8 | Outstate | Out-of-state tuition (USD) |
| 9 | Room.Board | Room and board costs (USD) |
| 10 | Books | Estimated book costs (USD) |
| 11 | Personal | Estimated personal spending (USD) |
| 12 | PhD | % of faculty with a PhD |
| 13 | Terminal | % of faculty with a terminal degree |
| 14 | S.F.Ratio | Student/faculty ratio |
| 15 | perc.alumni | % of alumni who donate |
| 16 | Expend | Instructional spending per student (USD) |
| 17 | Grad.Rate | Graduation rate (%) |
Now the first rows with every column (scroll the
table to the right), the type of each variable, and a summary of
Apps:
head(College) # first 6 colleges, all 18 columns
str(College) # type of every variable
## 'data.frame': 777 obs. of 18 variables:
## $ Private : Factor w/ 2 levels "No","Yes": 2 2 2 2 2 2 2 2 2 2 ...
## $ Apps : num 1660 2186 1428 417 193 ...
## $ Accept : num 1232 1924 1097 349 146 ...
## $ Enroll : num 721 512 336 137 55 158 103 489 227 172 ...
## $ Top10perc : num 23 16 22 60 16 38 17 37 30 21 ...
## $ Top25perc : num 52 29 50 89 44 62 45 68 63 44 ...
## $ F.Undergrad: num 2885 2683 1036 510 249 ...
## $ P.Undergrad: num 537 1227 99 63 869 ...
## $ Outstate : num 7440 12280 11250 12960 7560 ...
## $ Room.Board : num 3300 6450 3750 5450 4120 ...
## $ Books : num 450 750 400 450 800 500 500 450 300 660 ...
## $ Personal : num 2200 1500 1165 875 1500 ...
## $ PhD : num 70 29 53 92 76 67 90 89 79 40 ...
## $ Terminal : num 78 30 66 97 72 73 93 100 84 41 ...
## $ S.F.Ratio : num 18.1 12.2 12.9 7.7 11.9 9.4 11.5 13.7 11.3 11.5 ...
## $ perc.alumni: num 12 16 30 37 2 11 26 37 23 15 ...
## $ Expend : num 7041 10527 8735 19016 10922 ...
## $ Grad.Rate : num 60 56 54 59 15 55 63 73 80 52 ...
summary(College$Apps)
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 81 776 1558 3002 3624 48094
sum(is.na(College))
## [1] 0
dim shows 777 rows and 18 columns (1
response + 17 predictors). names and the table above list
all of them.Private is a Yes/No
(factor) variable. R automatically turns it into a 0/1 dummy
(PrivateYes).Apps ranges from 81 to over 48,000 and is
right-skewed (the mean is higher than the median). This
is why the errors will look big in absolute numbers.Exercise: Split the data set into a training set and a test set.
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.Answer to (a): the training set has 544 colleges (70%) and the test set has 233 colleges (30%).
Exercise: Fit a linear model using least squares on the training set, and report the test error obtained.
OLS chooses the coefficients that make the sum of squared errors (RSS) as small as possible:
\[\text{minimize } \text{RSS} = \sum_{i=1}^{n}\left(y_i - \beta_0 - \beta_1 x_{i1} - \beta_2 x_{i2} - \dots - \beta_{17} x_{i17}\right)^2\]
In words: find the weights \(\beta_j\) so that the predictions are as close as possible to the real values on the training colleges.
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
Check of the MSE formula. We can compute the same number step by step: errors, then squared errors, then the average.
errors <- te$Apps - ols_pred # actual minus predicted, for every test college
mean(errors^2) # average of squared errors = MSE
## [1] 1266407
sqrt(mean(errors^2)) # RMSE
## [1] 1125.347
all.equal(mean(errors^2), mse_ols) # TRUE means it matches the helper function
## [1] TRUE
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.
Predicted vs actual on the test set. Each dot is one test college. If a prediction were perfect, the dot would sit on the red line.
plot(te$Apps, ols_pred,
xlab = "Actual Apps", ylab = "Predicted Apps (OLS)",
main = "OLS: 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
How to read it: most dots follow the red line closely, so the OLS guesses are good. The dots spread out more for bigger colleges: small colleges (bottom left) are predicted very accurately, while a few large colleges are missed by several thousand applications (for example, some colleges with 14,000–16,000 actual applications are predicted at only 6,000–10,000). Also, a few very small colleges get a slightly negative prediction, which is impossible for a count. This is a limit of a plain linear model.
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
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.
Answer to (b): the least squares test error (MSE) is 1,266,407 (RMSE = 1125 applications).
Exercise: Fit a ridge regression model on the training set, with λ chosen by cross-validation. Report the test error obtained.
Ridge adds a penalty for big coefficients to the OLS criterion:
\[\text{minimize } \text{RSS} + \lambda \sum_{j=1}^{17} \beta_j^2\]
The second term is the penalty, and \(\lambda \ge 0\) is its
strength. With \(\lambda =
0\) we get plain OLS, and a bigger \(\lambda\) shrinks the coefficients more
(toward 0, but never exactly to 0). 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
lambda.min (lowest error). The
right dashed line is lambda.1se (the simplest model within
1 standard error).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.
Answer to (c): λ chosen by cross-validation = 367. The ridge test error (MSE) is 1,125,664 (RMSE = 1061 applications).
Exercise: Fit a lasso model on the training set, with λ chosen by cross-validation. Report the test error obtained, along with the number of non-zero coefficient estimates.
Lasso uses the absolute value of the coefficients in the penalty:
\[\text{minimize } \text{RSS} + \lambda \sum_{j=1}^{17} |\beta_j|\]
Unlike ridge, this penalty can set some coefficients exactly to 0, so lasso also does variable selection. Compare the two penalties: ridge uses \(\beta_j^2\) (shrinks), lasso uses \(|\beta_j|\) (shrinks and can delete).
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
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)
Compare the three columns.
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.0 in the Lasso column means the variable was removed.
Removed here: Personal.Answer to (d): λ chosen by cross-validation = 1.96. The lasso test error (MSE) is 1,259,544 (RMSE = 1122 applications), and the number of non-zero coefficient estimates is 16 (out of 17 predictors).
Exercise: Fit a PCR model on the training set, with M chosen by cross-validation. Report the test error obtained, along with the value of M selected by cross-validation.
PCA combines the correlated predictors into a few uncorrelated components, ordered by how much variation of the predictors they capture. Each component is a weighted mix of the predictors:
\[Z_m = \sum_{j=1}^{17} \phi_{jm}\, x_j \qquad (m = 1, 2, \dots, 17)\]
PCR then regresses Apps on the first M
components only:
\[\hat{y} = \theta_0 + \theta_1 Z_1 + \theta_2 Z_2 + \dots + \theta_M Z_M\]
The weights \(\phi_{jm}\) are chosen
from the predictors alone (without looking at Apps). With
\(M = 17\) we use all components, which
gives the same fit as OLS. 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
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.
Answer to (e): the value of M selected by cross-validation is 17. The PCR test error (MSE) is 1,266,407 (RMSE = 1125 applications).
Exercise: Fit a PLS model on the training set, with M chosen by cross-validation. Report the test error obtained, along with the value of M selected by cross-validation.
PLS uses the same form as PCR:
\[Z_m = \sum_{j=1}^{17} \phi_{jm}\, x_j \qquad \text{and} \qquad \hat{y} = \theta_0 + \theta_1 Z_1 + \dots + \theta_M Z_M\]
The difference is how the weights \(\phi_{jm}\) are chosen: PLS builds the
components using Apps as well (predictors
that are strongly related to Apps get more weight), 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
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
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.)
Answer to (f): the value of M selected by cross-validation is 17. The PLS test error (MSE) is 1,266,407 (RMSE = 1125 applications).
Exercise: Comment on the results obtained. How accurately can we predict the number of college applications received? Is there much difference among the test errors resulting from these five approaches?
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
Question 1: How accurately can we predict the number of college applications received?
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
Appshas 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.Question 2: Is there much difference among the test errors resulting from these five approaches?
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.
Why are the differences small, and why does ridge win?
Accept,Enroll,F.Undergrad,Top10perc,Top25perc). Ridge shrinks these correlated coefficients together and gives more stable predictions, while lasso and OLS do not.Which model 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.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.