Cross-Validation is a data partitioning method that can be used to:
- Assess the stability of parameter estimates
- Assess the accuracy of classification algorithms
- Assess the addequacy of a fitted model
Modelling the correct functional form
library(DAAG);attach(ironslag);summary(chemical);summary(magnetic)
The following objects are masked from ironslag (pos = 5):
chemical, magnetic
Min. 1st Qu. Median Mean 3rd Qu. Max.
10.0 16.0 21.0 21.1 25.0 32.0
Min. 1st Qu. Median Mean 3rd Qu. Max.
10.0 16.0 20.0 20.8 23.0 40.0
a <- seq(10, 40, .1) #sequence for plotting fits
L1 <- lm(magnetic ~ chemical)
yhat1 <- L1$coef[1] + L1$coef[2] * a
L2 <- lm(magnetic ~ chemical + I(chemical^2))
yhat2 <- L2$coef[1] + L2$coef[2] * a + L2$coef[3] * a^2
L3 <- lm(log(magnetic) ~ chemical)
logyhat3 <- L3$coef[1] + L3$coef[2] * a
yhat3 <- exp(logyhat3)
L4 <- lm(log(magnetic) ~ log(chemical))
yhat4 <- L4$coef[1] + L4$coef[2] * log(a)
par(mfrow = c(2, 2)) #layout for graphs
plot(chemical, magnetic, main="Linear", pch=16)
lines(a, yhat1, lwd=2)
plot(chemical, magnetic, main="Quadratic", pch=16)
lines(a, yhat2, lwd=2)
plot(chemical, magnetic, main="Exponential", pch=16)
lines(a, yhat3, lwd=2)
plot(log(chemical), log(magnetic), main="Log-Log", pch=16)
lines(log(a), yhat4, lwd=2)
par(mfrow = c(1, 1)) #restore display
LS0tCnRpdGxlOiAiQ3Jvc3MtVmFsaWRhdGlvbiBpbiBQcmFjdGljZSBieSBNaWd1ZWwgQW5nZWwgTHVxdWUgRmVybmFuZGV6IgpvdXRwdXQ6IGh0bWxfbm90ZWJvb2sKLS0tCgojIyNDcm9zcy1WYWxpZGF0aW9uIGlzIGEgZGF0YSBwYXJ0aXRpb25pbmcgbWV0aG9kIHRoYXQgY2FuIGJlIHVzZWQgdG86CiogQXNzZXNzIHRoZSBzdGFiaWxpdHkgb2YgcGFyYW1ldGVyIGVzdGltYXRlcwoqIEFzc2VzcyB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