在base R中,很容易使用anova()函数比较两个模型并进行F检验。
library(MASS)
lm.fit1 <- lm(medv ~ . , data = Boston)
lm.fit1a <- update(lm.fit1, ~ . - age - black)
anova(lm.fit1a, lm.fit1)如果我使用的是tidymodels工作流。我如何做同样的比较?我的代码是这样的:
library(tidymodels)
lm_spec <- linear_reg() %>%
set_mode("regression") %>%
set_engine("lm")
the_rec <- recipe(medv ~ ., data = Boston)
the_workflow <- workflow() %>%
add_recipe(the_rec) %>%
add_model(lm_spec)
the_workflow_fit1 <-
fit(the_workflow, data = Boston)
tidy(the_workflow_fit1)
the_workflow_fit1a <-
the_workflow_fit1 %>%
update_recipe(the_rec %>% step_rm(age, black)) %>%
fit(data = Boston)
tidy(the_workflow_fit1a)我不知道如何提取正确的对象(thingy)来提供这样的语句:
anova(the_workflow_fit1a$thingy, the_workflow_fit1$thingy)我需要的东西是什么?在tidymodels生态系统中,有没有一种优雅的方法来实现这一点呢?
发布于 2021-10-24 20:56:05
几个小时后,@juliasilge https://github.com/tidymodels/workflows/issues/54向我介绍了pull_workflow_fit(),我有了一个tidymodels解决方案。
基本R代码:
library(MASS)
lm.fit1 <- lm(medv ~ . , data = Boston)
lm.fit1a <- update(lm.fit1, ~ . - age - black)
anova(lm.fit1a, lm.fit1)可以在tidymodels中使用以下命令完成:
library(tidymodels)
lm_spec <- linear_reg() %>%
set_mode("regression") %>%
set_engine("lm")
the_rec <- recipe(medv ~ ., data = Boston)
the_workflow <- workflow() %>%
add_recipe(the_rec) %>%
add_model(lm_spec)
the_workflow_fit1 <-
fit(the_workflow, data = Boston) %>%
extract_fit_parsnip()
the_workflow_fit1a <-
the_workflow %>%
update_recipe(
the_rec %>% step_rm(age, black)
) %>%
fit(data = Boston) %>%
extract_fit_parsnip()
anova(the_workflow_fit1a$fit, the_workflow_fit1$fit)发布于 2021-10-24 15:44:40
我不完全熟悉tidymodels生态系统,因此我不确定这就是你想要的优雅的解决方案。
我深入研究了object the_workflow_fit1a,发现子集.$fit$fit$fit服务于anova函数所需的lm对象。
因此,这样就可以考虑一种解决方案;
models <- list(the_workflow_fit1,the_workflow_fit1a)
models2 <- lapply(models,function(x) x$fit$fit$fit)
anova(models2[[1]],models2[[2]])输出;
Res.Df RSS Df `Sum of Sq` F `Pr(>F)`
<dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 492 11079. NA NA NA NA
2 494 11351. -2 -272. 6.05 0.00254https://stackoverflow.com/questions/69696707
复制相似问题