Investigation: Cross-validation#

Resampling estimates performance for a specified training procedure and sampling scheme. Separate fitting, tuning, and final evaluation. Preprocessing, feature selection, and prompt selection belong inside training-side resampling when they are learned from data.

Question. Compare row-wise and participant-wise splits, tune a polynomial using grouped folds, and evaluate the selected model on untouched participants. Contrast ordinary and nested cross-validation.

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)
d <- simulate_trials()
outer <- split_groups(d$subject,seed=432)
train <- d[outer$train,]; test <- d[outer$test,]
fold <- group_folds(train$subject,k=5)
candidates <- c(1,2,3)
cv <- sapply(candidates,function(degree) {
  out <- rep(NA_real_,nrow(train))
  for(f in unique(fold)) {
    a <- which(fold!=f); v <- which(fold==f)
    stopifnot(length(intersect(train$subject[a],train$subject[v]))==0)
    fit <- lm(rt~poly(frequency,degree)+length,train[a,])
    out[v] <- predict(fit,train[v,])
  }
  mse(train$rt,out)
})
data.frame(degree=candidates,validation_mse=cv)
best <- candidates[which.min(cv)]
final <- lm(rt~poly(frequency,best)+length,train)
c(selected_degree=best,test_mse=mse(test$rt,predict(final,test)))
A data.frame: 3 × 2
degreevalidation_mse
<dbl><dbl>
15423.383
25411.974
35410.613
selected_degree
3
test_mse
7471.75271535404

Why the split unit matters#

A subject-specific predictor can work when the same subject occurs on both sides, yet offer no information about a new person. The next contrast estimates two different targets; the difference is not automatically an implementation error.

row_split <- split_groups(d$trial_id,seed=432)
predict_known_subject <- function(train,test) {
  means <- tapply(train$rt,train$subject,mean)
  pred <- as.numeric(means[as.character(test$subject)])
  pred[is.na(pred)] <- mean(train$rt)
  pred
}
rbind(row_split=c(mse=mse(d$rt[row_split$test],predict_known_subject(d[row_split$train,],d[row_split$test,]))),new_subject=c(mse=mse(test$rt,predict_known_subject(train,test))))
A matrix: 2 × 1 of type dbl
mse
row_split 6618.58
new_subject10529.57

Nested evaluation and other sampling schemes#

The initial outer holdout evaluates the complete inner selection procedure. For nested cross-validation, repeat this entire procedure for each outer assessment fold, retuning only within its analysis portion. Do not average the minimum inner score and call it final performance. Use chronological splits for future observations, site holdouts for new sites, and crossed holdouts when both subjects and items must be new.

LOOCV has K=n folds. Replacing it with 5-fold CV decreases K; the variance of the resulting estimate depends on the problem and dependence among fitted models. Use common folds when comparing candidates. Polynomial degree 2 is quadratic and degree 3 cubic.

Interpret and verify#

State the deployment population, draw the split diagram, and assert group disjointness. Explain whether both participants and items must be new.

Failure to consider: Random folds can share participants, items, families, or future information across analysis and assessment sets. Neither more folds nor LOOCV automatically gives the most useful estimate.

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.

Generalization depends on the units defined earlier; resampling also supplies tools for uncertainty and hypothesis testing.

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     

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 Ven Popov and edited by Krista Bond, Charles Wu, Patience Stevens, Amy Sentis, and Fiona Horner.

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