Investigation: Principal component methods

Investigation: Principal component methods#

PCA compresses variation in predictors. The directions with the most predictor variance need not predict the outcome or correspond to meaningful constructs. PCR chooses predictive complexity after unsupervised projection; PLS learns directions using the outcome.

Question. Calculate explained variance correctly, then construct a low-variance direction carrying the predictive signal. Tune PCR components within training-side folds.

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)
pc <- prcomp(iris[,1:4],scale.=TRUE)
explained <- pc$sdev^2/sum(pc$sdev^2)
stopifnot(abs(sum(explained)-1)<1e-12)
data.frame(component=seq_along(explained),variance_fraction=explained,cumulative=cumsum(explained))
plot(cumsum(explained),type="b",ylim=c(0,1),xlab="Number of components",ylab="Cumulative predictor variance")
A data.frame: 4 × 3
componentvariance_fractioncumulative
<int><dbl><dbl>
10.7296244540.7296245
20.2285076180.9581321
30.0366892190.9948213
40.0051787091.0000000
../_images/e16d6474a715ece015740cb693e0654368bc350ae275cd43f336c60113996629.png

Predictor variance need not be predictive information#

The next simulator makes one high-variance direction irrelevant and a low-variance direction predictive. Scaling is a scientific choice: it changes which units define variance. This example deliberately does not scale, to expose the difference.

n <- 180
x <- cbind(high_variance=rnorm(n,0,10),low_variance=rnorm(n,0,.1))
y <- 15*x[,2]+rnorm(n,0,.3)
s <- split_groups(seq_len(n))
train_x <- x[s$train,,drop=FALSE]; train_y <- y[s$train]
fold <- group_folds(seq_along(train_y))
cv <- sapply(1:2,function(k) {
  pred <- rep(NA_real_,length(train_y))
  for(f in unique(fold)) {
    a <- which(fold!=f); v <- which(fold==f)
    pca <- prcomp(train_x[a,,drop=FALSE],scale.=FALSE)
    za <- as.data.frame(predict(pca,train_x[a,,drop=FALSE])[,seq_len(k),drop=FALSE]); za$y <- train_y[a]
    zv <- as.data.frame(predict(pca,train_x[v,,drop=FALSE])[,seq_len(k),drop=FALSE])
    pred[v] <- predict(lm(y~.,za),zv)
  }
  mse(train_y,pred)
})
best_k <- which.min(cv)
pca <- prcomp(train_x,scale.=FALSE)
za <- as.data.frame(predict(pca,train_x)[,seq_len(best_k),drop=FALSE]); za$y <- train_y
zt <- as.data.frame(predict(pca,x[s$test,,drop=FALSE])[,seq_len(best_k),drop=FALSE])
fit <- lm(y~.,za)
c(selected_components=best_k,test_mse=mse(y[s$test],predict(fit,zt)))
data.frame(components=1:2,validation_mse=cv)
selected_components
2
test_mse
0.106515826883663
A data.frame: 2 × 2
componentsvalidation_mse
<int><dbl>
12.04167074
20.07729861
library(pls) # MSEP evaluates an internal helper in the attached package.
# PLS uses training outcomes to learn directions; keep the same fold assignment.
train <- data.frame(y=train_y,train_x)
test <- data.frame(x[s$test,,drop=FALSE])
pls_fit <- pls::plsr(y~.,data=train,scale=FALSE,ncomp=2,validation="CV",segments=split(seq_along(fold),fold))
validation <- drop(pls::MSEP(pls_fit,estimate="CV")$val)
# Validation includes the intercept-only model before components 1 and 2.
pls_k <- which.min(validation[-1])
pls_pred <- drop(predict(pls_fit,newdata=test,ncomp=pls_k))
c(pls_components=pls_k,pls_test_mse=mse(y[s$test],pls_pred))
Attaching package: ‘pls’
The following object is masked from ‘package:stats’:

    loadings
pls_components.2 comps
2
pls_test_mse
0.106515826883663

This is a prespecified PCR/PLS comparison, not a license to tune on its final test results. In the HCP extension, compare brain-volume reconstruction with prediction of Flanker performance, using appropriate group splits if the metadata support them. PCA of embeddings likewise visualizes a representation, not necessarily natural categories or mechanisms.

Interpret and verify#

Compare components needed for predictor reconstruction and outcome prediction; justify the difference. Distinguish measured brain volumes from psychological constructs.

Failure to consider: A convincing two-dimensional cluster plot does not establish categories. Choosing components from all data before validation leaks information about the assessment sample.

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.

Compare compression with shrinkage and return to uncertainty in the Understanding part.

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     

other attached packages:
[1] pls_2.8-1

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    

Attribution#

Notebook authored by Patience Stevens and edited by Amy Sentis.

Revised investigation: 2026 course revision. Original authorship is retained; examples and explanatory text have been updated.