I'm trying to do leave one out cross validation of non linear regression and plot the optimal fit. I feel like my loocv and plot functions are totally wrong. Could anybody clarify what I'm doing wrong?
data(Boston, package='MASS')
y <- Boston$nox
x <- Boston$dis
n <- length(x)
nla <- n
las <- seq(0, .85, length=nla)
cvs <- rep(0, nla)
for(j in 1:nla) {
prs <- rep(0,n)
for(i in 1:n) {
yi <- y[-i]
xi <- x[-i]
d <- nls(y~ A + B * exp(C * x), start=list(A=0.5, B=0.5, C=-0.5))
prs[i] <- predict(d, newdata=data.frame(xi=x[i]))
}
cvs[j] <- mean( (y - prs)^2 )
}
cvs[j]
plot(y~x, pch=19, col='gray', cex=1.5,xlab='dis', ylab='nox')
d <- nls(y~ A + B * exp(C * x), start=list(A=0.5, B=0.5, C=-0.5))
lines(predict(d)[order(x)]~sort(x), lwd=4, col='black')