# Now we visualize the different models trained, one for each CV fold
for (i in 1:k) {
dat.tr = dat[inds!=i,] # Training data
dat.te = dat[inds==i,] # Test data
# Train our models
lm.1.minus.i = lm(y ~ x, data=dat.tr)
lm.10.minus.i = lm(y ~ poly(x,10), data=dat.tr)
# Plot fitted models
par(mfrow=c(1,2)); cols = c("red","gray")
plot(dat$x, dat$y, pch=20, col=cols[(inds!=i)+1], main=paste("Fold",i))
lines(xx, predict(lm.1.minus.i, data.frame(x=xx)), lwd=2, lty=2)
legend("topleft", legend=c(paste("Fold",i),"Other folds"), pch=20, col=cols)
text(0, -6, label=paste("Fold",i,"error:",
round(mean((dat.te$y - pred.mat[inds==i,1])^2),3)))
plot(dat$x, dat$y, pch=20, col=cols[(inds!=i)+1], main=paste("Fold",i))
lines(xx, predict(lm.10.minus.i, data.frame(x=xx)), lwd=2, lty=2)
legend("topleft", legend=c(paste("Fold",i),"Other folds"), pch=20, col=cols)
text(0, -6, label=paste("Fold",i,"error:",
round(mean((dat.te$y - pred.mat[inds==i,2])^2),3)))
}




##
Part III
Smoothing example