【发布时间】:2019-06-26 04:09:19
【问题描述】:
我正在尝试使用一些公式来拟合几个机器学习模型,并将它们作为 list_column 对象存储在 tibble 中。
我试图修改“R for Datascience”(第 25 章:许多模型)一书中引用的代码,但它只给了我最后的输出。请参阅下面的代码以获取更多详细信息。我们以 gapminder 包中的 gapminder 数据集为例。
lab_formula <- as.formula("pop ~ lifeExp ")
temp_formula <- as.formula("gdppercap ~ year")
formula_list <- list(lab_formula,temp_formula)
library(gapminder)
by_country <- gapminder %>%
dplyr :: group_by(country, continent) %>%
nest()
country_model <- function(df) {
for (i in formula_list) {
lm(formula=formula[i], data = df)
randomForest(formula=formula[i], data = df)
gbm(formula=formula[i], data = df, n.minobsinnode = 2)
}
}
by_country <- by_country %>%
mutate(model = map(data, country_model))
by_country
# A tibble: 142 x 4
country continent data model
<fct> <fct> <list> <list>
1 Afghanistan Asia <tibble [12 x 4]> <S3: gbm>
2 Albania Europe <tibble [12 x 4]> <S3: gbm>
3 Algeria Africa <tibble [12 x 4]> <S3: gbm>
4 Angola Africa <tibble [12 x 4]> <S3: gbm>
5 Argentina Americas <tibble [12 x 4]> <S3: gbm>
6 Australia Oceania <tibble [12 x 4]> <S3: gbm>
7 Austria Europe <tibble [12 x 4]> <S3: gbm>
8 Bahrain Asia <tibble [12 x 4]> <S3: gbm>
9 Bangladesh Asia <tibble [12 x 4]> <S3: gbm>
10 Belgium Europe <tibble [12 x 4]> <S3: gbm>
# ... with 132 more rows
There is no error code but it does not achieve my objective of training the 3 machine learning models (LM, RF, GBM) with the different variables.
【问题讨论】:
-
您的函数
country_model不输出任何内容。您应该创建一个对象并将其传递给return。此外,您没有在创建模型时将模型存储在对象中,那么您会输出什么?您的模型可能确实运行了,但您没有得到任何输出,因为您没有将它们分配给一个对象,然后从函数中返回它。 -
嗨 Dij,变量 'by_country' 将输出我的模型结果。请查看已编辑的问题以使其更清楚。
-
我认为您正在覆盖函数调用中的每个模型,以便最终得到最后一个。