如何将大量模型传递给gather_predictions

时间:2016-12-16 15:07:21

标签: r tidyverse

modelr包中,函数gather_predictions可用于将多个模型的预测添加到数据框中,但我不确定如何在函数调用中指定这些模型。帮助文档提供了以下示例:

df <- tibble::data_frame(
  x = sort(runif(100)),
  y = 5 * x + 0.5 * x ^ 2 + 3 + rnorm(length(x))
)

m1 <- lm(y ~ x, data = df)
grid <- data.frame(x = seq(0, 1, length = 10))
grid %>% add_predictions(m1)

m2 <- lm(y ~ poly(x, 2), data = df)
grid %>% spread_predictions(m1, m2)
grid %>% gather_predictions(m1, m2)

这里的模型在函数调用中特别提到。如果我们有一些我们想要预测的模型,那就行得很好,但是如果我们有大量或未知数量的模型呢?在这种情况下,手动指定模型不再可行。

参数段的帮助文档短语似乎表明您需要将每个模型添加为单独的参数。

  

gather_predictions和spread_predictions采用多种模式。该   name将取自名称的参数名称   模型。

例如,在gather_predictions中输入模型列表不起作用。

是否有一些简单的方法可以将一个列表/大量模型输入到gather_predictions?

列表中10个模型的示例:

modelslist <- list()
for (N in 1:10) {
  modelslist[[N]] <- lm(y ~ poly(x, N), data = df)
}

如果以比列表更好的方式存储模型,那也没关系。

2 个答案:

答案 0 :(得分:1)

m <- grid %>% gather_predictions(lm(y ~ poly(x, 1), data = df))
for (N in 2:10) {
  m <- rbind(m, grid %>% gather_predictions(lm(y ~ poly(x, N), data = df)))
}

答案 1 :(得分:1)

有解决此问题的方法。我的方法是:  1.建立具有特定名称的模型列表  2.使用经过调整的modelr :: gather_predictions()版本将列表中的所有模型应用于数据

# prerequisites
library(tidyverse)
set.seed(1363)    

# I'll use generic name 'data' throughout the code, so you can easily try other datasets.
# for this example I'll use your data df
data=df

# data visualization
ggplot(data, aes(x, y)) + 
        geom_point(size=3)

your sample data

# build a list of models
models <-vector("list", length = 5)
model_names <- vector("character", length=5)
for (i in 1:5) {
        modelformula <- str_c("y ~ poly(x,", i, ")", sep="")
        models[[i]] <- lm(as.formula(modelformula), data = data)
        model_names[[i]] <- str_c('model', i) # remember we name the models here sequantially
}

# apply names to the models list
names(models) <- model_names

# this is modified verison of modelr::gather_predictions() in order to accept list of models
gather.predictions <- function (data, models, .pred = "pred", .model = "model") 
{
        df <- map2(models, .pred, modelr::add_predictions, data = data)
        names(df) <- names(models)
        bind_rows(df, .id = .model)
}

# the rest is the same as modelr's function...
grids <- gather.predictions(data = data, models = models, .pred = "y")

ggplot(data, aes(x, y)) + 
        geom_point() +
        geom_line(data = grids, colour = "red") +
        facet_wrap(~ model)

example of polynomial models (degree 1:5) applied to your sample data

旁注:我选择字符串来构建模型的原因很充分……进行讨论。