如何执行 K 折交叉验证和理解输出

How to perform a K-fold cross validation and understanding the outputs

我一直在尝试在 R 中对我创建的数据集执行 k 折交叉验证。此数据的link如下:

https://drive.google.com/open?id=0B6vqHScIRbB-S0ZYZW1Ga0VMMjA

我使用了以下代码:

    library(DAAG)
    six = read.csv("six.csv") #opening file

    fit <- lm(Height ~ GLCM.135 + Blue + NIR, data=six) #applying a regression model
    summary(fit) # show results

    CVlm(data =six, m=10, form.lm = formula(Height ~  GLCM.135 + Blue + NIR )) # 10 fold cross validation 

这会产生以下输出(摘要版本)

    Sum of squares = 7.37    Mean square = 1.47    n = 5 

    Overall (Sum over all 5 folds) 
    ms 
    3.75 

    Warning message:

    In CVlm(data = six, m = 10, form.lm = formula(Height ~ GLCM.135 +  : 

    As there is >1 explanatory variable, cross-validation
    predicted values for a fold are not a linear function
    of corresponding overall predicted values.  Lines that
    are shown for the different folds are approximate

我不明白 ms 值指的是什么,因为我在互联网上看到了不同的解释。据我了解,K 折交叉验证会为指定模型产生整体 RMSE 值(这是我在研究中试图获得的值)。

我也不明白为什么当我在代码中指定了 10 折交叉验证时,生成的结果会产生 总体(所有 5 折的总和)

如果有人能提供帮助,我们将不胜感激。

当我 运行 同样的东西时,我看到它确实做了 10 次折叠,但最终打印的输出与你的相同 ("Sum over all 5 folds")。 "ms" 是均方预测误差。 3.75 的值也不完全是所有 10 次折叠的简单平均值(得到 3.67):

msaverage <- (1.19+6.04+1.26+2.37+3.57+5.24+8.92+2.03+4.62+1.47)/10
msaverage

请注意,平均和大多数折叠都高于 "Residual standard error" (1.814)。这是我们所期望的,因为 CV 误差表示模型可能在 "test" 数据(不是用于训练模型的数据)上的性能。例如,在 Fold 10 上,注意计算的残差是基于未在该模型的训练中使用的预测观察值(5 个观察值):

fold 10 
Observations in test set: 5 
           12    14     26    54    56
Predicted   20.24 21.18 22.961 18.63 17.81
cvpred      20.15 21.14 22.964 18.66 17.86
Height      21.98 22.32 22.870 17.12 17.37
CV residual  1.83  1.18 -0.094 -1.54 -0.49

Sum of squares = 7.37    Mean square = 1.47    n = 5 

我们收到的这个警告似乎也很常见——也在这篇文章中看到了:http://www.rpubs.com/jmcimula/xCL1aXpM3bZ

我可以建议的一件事可能对您有用,即在线性回归的情况下,留一法交叉验证 (loocv) 有一个封闭形式的解决方案,无需实际拟合多个模型。

predictedresiduals <- residuals(fit)/(1 - lm.influence(fit)$hat)
PRESS <- sum(predictedresiduals^2)
PRESS  #Predicted Residual Sum of Squares Error
fitanova <- anova(fit)  #Anova to get total sum of squares
tss <- sum(fitanova$"Sum Sq")   #Total sum of squares
predrsquared <- 1 - PRESS/(tss)
predrsquared

请注意,此值为 0.574,而原始 Rsquared 为 0.6422

为了更好地传达 RMSE 的概念,查看预测残差的分布很有用:

hist(predictedresiduals)

RMSE 可以简单地计算为:

sd(predictedresiduals)