我想使用 R 中的插入符号获得跨 CV 重复的平均预测值。
require("caret")
data("iris")
fitControl <- trainControl(method = "repeatedcv",
number = 10,
repeats = 10, savePredictions = 'final')
model.cv <- train(Sepal.Length ~ Sepal.Width,
data = iris,
method = "lm",
trControl = fitControl)
head(model.cv$pred)
# intercept pred obs rowIndex Resample
#1 TRUE 5.809386 4.7 3 Fold01.Rep01
#2 TRUE 5.838487 4.6 4 Fold01.Rep01
#3 TRUE 5.460174 5.7 16 Fold01.Rep01
#4 TRUE 5.634780 5.7 19 Fold01.Rep01
#5 TRUE 5.722083 5.2 28 Fold01.Rep01
#6 TRUE 6.071295 4.5 42 Fold01.Rep01
现在我想获得每个示例的所有 10 个预测的平均值。我可以通过迭代以下示例来做到这一点,但我认为必须有更好的更整洁的方式。
mean(model.cv$pred[model.cv$pred$rowIndex==1, "pred"])
#[1] 5.745675
编辑
按照@Obim 的回答,我测试了三个提议的解决方案的时间安排。dplyr
版本更快。请注意,我稍微修改了sapply
版本,在唯一性上添加了一个排序,rowINdex
以保持其输出的一致性和可解释性。
library("plyr")
library("dplyr")
library("tictoc")
tic("plyr")
for(i in 1:100) meansplyr = ddply(model.cv$pred, ~rowIndex, summarise, mean = mean(pred))
toc()
#plyr: 5.56 sec elapsed
tic("dplyr")
for(i in 1:100) meansdplyr = model.cv$pred %>% group_by(rowIndex) %>% summarise(pred = mean(pred))
toc()
#dplyr: 0.08 sec elapsed
tic("sapply")
for(i in 1:100) {
meanssapply = sapply(
X = sort(unique(model.cv$pred$rowIndex)), # added sort to keep the output consistent
FUN = function(x){mean(model.cv$pred$pred[model.cv$pred$rowIndex %in% x])}
)
}
toc()
#sapply: 0.73 sec elapsed
# the outputs are exactly the same
sum(abs(meansplyr$mean - meansdplyr$pred))
#[1] 0
sum(abs(meansplyr$mean - meanssapply))
#[1] 0