【发布时间】:2020-03-22 13:25:45
【问题描述】:
如何矢量化这个循环?当我有向后逐步回归的循环时,运行回归需要 15 分钟以上。 (我的完整数据集有超过 4000 个观察值和 20 多个自变量。)知道如何将其向量化吗?我对整个概念很陌生。
我已经考虑将其设为函数,然后使用 ifelse 语句进行训练和验证。但是,我无法让它在代码中工作。有什么想法吗?
这是一个小数据集:
name <- c("Joe I.", "Joe I.", "Joe I.", "Joe I.", "Jane P.", "Jane P.", "Jane P.", "Jane P.",
"John K.", "John K.", "John K.", "John K.")
name_id <- c(1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3)
grade <- c(80, 99, 70, 65, 88, 90, 76, 65, 67, 68, 89, 67)
score <- c(82, 93, 72, 61, 89, 93, 71, 63, 64, 65, 82, 62)
attendance <- c(80, 99, 82, 62, 70, 65, 88, 90, 76, 93, 71, 99)
participation <- c(71, 63, 64, 71, 99, 76, 65, 67, 93, 72, 68, 89)
df <- cbind(name, name_id, class, grade, score, attendance, participation)
df <- as.data.frame(df)
df$name_id <- as.numeric(df$name_id)
df$grade <- as.numeric(df$grade)
df$score <- as.numeric(df$score)
df$attendance <- as.numeric(df$attendance)
df$participation <- as.numeric(df$participation)
这是循环:
magic_for(print, silent = TRUE)
for(i in 1:3){
validation = df[df$name_id == (i),]
training = df[df$name_id != (i),]
m = lm(score ~ grade + attendance, participation, data = training)
stepm <- stepAIC(m, direction = "backward", trace = FALSE)
pred1 <- predict(stepm, validation)
print(pred1)
}
options(max.print=999999)
pred1 <- magic_result_as_dataframe()
【问题讨论】:
-
循环中唯一昂贵的部分是对
lm和stepAIC的调用。lm有更快的替代方案。看这里:stackoverflow.com/questions/25416413/…至于stepAIC,考虑glmnet包中的类似功能,它是基于FORTRAN构建的,速度很快(talkstats.com/threads/…)
标签: r for-loop regression vectorization