Imagine you work for a university and want to guess how many students will apply to a college before the application season ends. You know some facts about each college: how many students it accepted, how much it spends per student, whether it is private, its tuition, and so on.
The College data set has exactly this kind of
information for 777 colleges in the USA. Our job is to
build a prediction machine: give it the facts about a
college, and it guesses Apps (the number of applications).
We build the machine in five different ways, then ask:
which one guesses best?
The simple plan:
| Word | Meaning in everyday language |
|---|---|
| Predictor | A fact we use to make the guess (e.g. number of students accepted). We have 17 of them. |
| Response | The thing we want to guess. Here it is Apps. |
| Training set | The colleges the machine is allowed to learn from. |
| Test set | The hidden colleges used only to check the machine honestly. |
| Test error (MSE) | How wrong the guesses are on average (bigger mistakes count extra). Smaller is better. |
| RMSE | The same error, but in normal units: “the guess is off by about this many applications.” |
| R² | A score from 0 to 1. Closer to 1 means the guesses follow reality more closely. 0.9 means “explains about 90% of the ups and downs.” |
| Overfitting | The machine memorizes the training colleges instead of learning the real pattern, so it does badly on new ones. |
| Cross-validation (CV) | A fair way to choose settings: split the training data into pieces, learn on some, check on the rest, and repeat. |
| Method | Everyday idea |
|---|---|
| Least squares (OLS) | The standard approach. Draw the best-fitting line (well, a flat surface in many dimensions) through the data. No restrictions. |
| Ridge | Same as OLS, but we say: “Don’t trust any single fact too much.” It calms down big, extreme weights. Useful when several facts say almost the same thing. |
| Lasso | Same, but also: “If a fact is not helping, ignore it completely.” So it can remove useless facts. |
| PCR | Many facts are repeats of each other (a big college has many
applicants and many accepted and many
enrolled). PCR first merges similar facts into a few “summary
scores”, then predicts from those. It decides the summaries
without looking at Apps. |
| PLS | Same as PCR, but the summary scores are built while keeping
an eye on Apps, so they are more useful for
guessing. |
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
What we see:
Apps).Apps itself is big.Private is a Yes/No fact. R automatically turns it into
a 0/1 number called PrivateYes.Why do we split? Think of a student preparing for an exam. If the exam has exactly the same questions as the practice book, a high score proves nothing, because the student may have just memorized the answers. To be fair, the exam must have new questions.
It is the same for our machine. If we test it on the colleges it learned from, it will look better than it really is. So we hide 30% of the colleges (the test set) and teach the machine with the other 70% (the training set).
set.seed(1) # fixes the "random" choice, so everyone gets the same split
n <- nrow(College)
train <- sample(n, round(0.7 * n)) # randomly pick 70% of the colleges for training
tr <- College[train, ] # training colleges
te <- College[-train, ] # all the other colleges = test colleges
c(training = nrow(tr), test = nrow(te))
## training test
## 544 233
# a small helper: "how wrong are the guesses on the test colleges, on average?"
test_mse <- function(pred) mean((te$Apps - pred)^2)
# ridge and lasso need the data as a plain table of numbers
x <- model.matrix(Apps ~ ., data = College)[, -1]
y <- College$Apps
What happened:
set.seed(1) is like fixing the shuffle of a deck of
cards. Anyone who runs this code gets the same split and the same
results.ols_fit <- lm(Apps ~ ., data = tr) # learn from the training colleges
ols_pred <- predict(ols_fit, newdata = te) # guess Apps for the hidden test colleges
mse_ols <- test_mse(ols_pred)
c(test_MSE = mse_ols, test_RMSE = sqrt(mse_ols))
## test_MSE test_RMSE
## 1266406.906 1125.347
In plain words: the machine learned from the 544 training colleges and then guessed the applications of the 233 hidden colleges. On average its guesses are off by about 1125 applications (RMSE). The error score (MSE) is 1,266,407. This number is not very meaningful by itself. It becomes useful when we compare it with the other methods.
Which facts matter most? Here are the facts that the model found really useful (statistically significant):
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 table: each row is a fact. The
Estimate column says how much the guess for
Apps changes when that fact goes up by one unit, while
everything else stays the same.
Accept (students
accepted). Each extra accepted student goes with about 1.7 more
applications. This makes sense: colleges that accept many
students are big and popular.Top10perc (share of new students from
the top 10% of their school) also pushes applications up.PrivateYes is negative: with the other
facts equal, private colleges get fewer applications
than public ones.Enroll, Top25perc,
Outstate (out-of-state tuition), Room.Board,
Expend (spending per student) and Grad.Rate
also play a role.The problem it solves: many of our facts are almost the same information. For example, a college with many accepted students usually also has many enrolled students and many undergraduates. When facts overlap like this, plain OLS can become confused. It may give one fact a huge positive weight and its twin a huge negative weight, and the two cancel each other. These extreme weights make the guesses unstable on new colleges.
What ridge does: it adds a “penalty” for big weights, which pushes all the weights toward zero (but never exactly to zero). The strength of the penalty is called λ (lambda). Small λ means almost normal OLS. Large λ means strong calming.
How do we choose λ? Not by guessing. We let cross-validation do it using only the training colleges: the computer tries many values of λ, tests each one fairly, and picks the one with the smallest error.
set.seed(1)
cv_ridge <- cv.glmnet(x[train, ], y[train], alpha = 0) # alpha = 0 means ridge
plot(cv_ridge)
best_lambda_ridge <- cv_ridge$lambda.min # the λ with the lowest CV error
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 horizontal axis is the penalty strength (on a log scale), and the vertical axis is the error. The red dots show the error for each λ. The error goes down, reaches a lowest point, and then goes up again:
Result: Ridge test error = 1,125,664, compared with OLS at 1,266,407. That is 11.1% better. In everyday terms, the typical mistake dropped from about 1125 to about 1061 applications. So calming the weights really helped on colleges the model had never seen.
Lasso is a cousin of ridge. The difference is in the kind of penalty. Ridge makes weights smaller. Lasso can make a weight exactly zero, which means that fact is thrown away. So lasso is also a tool for choosing which facts to keep.
set.seed(1)
cv_lasso <- cv.glmnet(x[train, ], y[train], alpha = 1) # alpha = 1 means 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) # how many facts survived (ignoring the intercept)
c(test_MSE = mse_lasso, test_RMSE = sqrt(mse_lasso), facts_kept = n_nonzero)
## test_MSE test_RMSE facts_kept
## 1259544.346 1122.294 16.000
How to read the plot: it is similar to the ridge plot, but the numbers along the top show how many facts are still in the model at each penalty strength. As the penalty grows (to the right), more and more facts are dropped.
Result: the best λ is small (1.96), so the lasso only did a very light clean-up. It kept 16 of the 17 facts. Its test error is 1,259,544, almost the same as OLS. The message is: almost all 17 facts are useful, so there is not much to throw away.
What if we want a simpler model? The “1 standard error” choice accepts a slightly worse error for a much simpler model:
lasso_pred_1se <- predict(cv_lasso, s = cv_lasso$lambda.1se, newx = x[-train, ])
c(test_MSE = test_mse(lasso_pred_1se),
facts_kept = sum(coef(cv_lasso, s = cv_lasso$lambda.1se)[-1] != 0))
## test_MSE facts_kept
## 1320249 3
With the bigger penalty, only a few facts remain, and the error is a bit higher. This is the usual trade-off: simpler model = slightly less accurate.
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 it: each row is a fact and each column is a method. Bigger numbers (in absolute value) mean the method trusts that fact more.
Accept went from about 1.7 (OLS)
to about 1.1, and Enroll even changed from negative to
positive. This happens because Accept and
Enroll carry overlapping information. OLS had to balance
them against each other with odd signs, and ridge shares the credit more
evenly.The idea with an example: suppose you are describing colleges with facts like number accepted, number enrolled, number of undergraduates. These three mostly say the same thing: “how big is this college?” PCR notices this and combines them into one summary score called a component. The first component captures the biggest pattern across all facts, the second captures the next biggest pattern, and so on.
Then PCR predicts Apps from the first M summary
scores. We must choose M: too few and we lose useful
information, too many and we are back to using everything. We choose M
by cross-validation.
One technical step: scale = TRUE puts every fact on the
same scale first. Without it, a fact measured in thousands (like
Expend) would dominate a fact measured from 0 to 100 (like
Grad.Rate) for no good reason.
set.seed(1)
pcr_fit <- pcr(Apps ~ ., data = tr, scale = TRUE, validation = "CV")
validationplot(pcr_fit, val.type = "MSEP", main = "PCR: error vs number of summary scores (M)")
M_pcr <- which.min(pcr_fit$validation$PRESS) # the 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 horizontal axis is M (how many summary scores we use), and the vertical axis is the error. Lower is better. The curve stays high for a long time and only drops sharply when M gets close to the maximum.
cv_rmse_pcr <- sqrt(pcr_fit$validation$PRESS / nrow(tr))
data.frame(M = c(1, 2, 5, 10, 15, 17), typical_error = round(cv_rmse_pcr[c(1, 2, 5, 10, 15, 17)]))
Result: cross-validation picks M = 17, which is all the summary scores. Using all of them is the same as using all the original facts, so PCR gives exactly the same answer as OLS (same test error, 1,266,407).
Why didn’t PCR help here? PCR builds its summary
scores by looking only at the facts, never at Apps. The
patterns that vary the most among colleges (mostly “how big is the
college”) are not necessarily the patterns that best predict
applications. Some small, quiet patterns turned out to be important, so
PCR had to keep almost all of them.
PLS is the smarter cousin of PCR. It also merges facts into summary
scores, but while doing so it checks how well each summary
predicts Apps. So the very first summary scores
are already the useful ones, and we usually need fewer of
them.
set.seed(1)
pls_fit <- plsr(Apps ~ ., data = tr, scale = TRUE, validation = "CV")
validationplot(pls_fit, val.type = "MSEP", main = "PLS: error vs number of summary scores (M)")
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: compare it with the PCR plot. PLS reaches a low error much sooner. The curve is almost flat after about M = 6. The typical CV error is about 1,170 at M = 6, and about 1,150 even with all 17.
Result: the strict lowest point is at M = 17, but M = 6 to 8 is almost as good. In practice we could choose a smaller M and get nearly the same accuracy with a much simpler model. Using all 17 summary scores makes PLS identical to OLS again.
PLS vs PCR with the same small M, on the test colleges (smaller number = better):
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
What this shows: when we use only a few summary scores, PLS is far better than PCR. For example, with 4 scores PLS has a much lower error. That is the whole point of PLS: its summaries are built to be useful for the goal. When M reaches 17, both become OLS and the difference disappears. (Reminder: M was chosen by cross-validation, not by looking at these test numbers.)
Now we put the five methods on the same scoreboard. All of them were scored on the same 233 hidden colleges.
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, " facts kept)"),
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 if we just guessed the average every time
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 facts kept) | 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 = "Typical error (number of applications)", main = "Typical guessing error by method")
One more picture, to see the guesses against reality. Each dot is a hidden college. If a guess were perfect, the dot would sit on the red line.
plot(te$Apps, ridge_pred, xlab = "Actual number of applications", ylab = "Predicted (Ridge)",
main = "Ridge: prediction vs reality on the test colleges",
pch = 19, col = rgb(0, 0, 1, 0.4))
abline(0, 1, col = "red", lwd = 2)
1. Can we predict the number of applications
accurately? Yes, quite well. The best method explains about
92% of the ups and downs of Apps on
colleges it has never seen, and the typical mistake is about
1061 applications. That might sound large, but remember
that colleges range from 81 to over 48,000 applications, so a mistake of
around 1,000 is small compared with that range. In the last picture,
most dots follow the red line closely. The very large colleges are the
hardest to guess.
2. Are the five methods very different? Mostly no. OLS, lasso, PCR and PLS give almost the same score (about 1,266,407; lasso is at 1,259,544). Ridge is the winner, with 1,125,664, which is about 11.1% better than OLS. That is a useful improvement, but not a dramatic one, because all the methods were already good.
3. Why are they so similar, and why does ridge win?
Accept, Enroll, F.Undergrad,
Top10perc, Top25perc). Ridge handles
overlapping facts best: it shares the credit between them instead of
letting them fight each other.4. Which model would we recommend?
Accept (students
accepted) is the strongest single clue for how many applications a
college gets.5. An honest warning. The exact numbers depend on which colleges ended up in the test set (we used one random split). With another split, the errors would change a bit, and since the methods are so close, even the ranking could change. To be extra sure, we could repeat the split many times or use k-fold cross-validation for the final comparison.
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