0

我有一个关于使用 ggeffects 进行预测的问题,如果我使用传统的 lm 拟合或提取的欧洲防风草模型拟合(尽管具有相同的系数),这会给我完全不同的结果。这是一个例子......

library(tidyverse)
library(tidymodels)
library(ggeffects)

test_df <- structure(list(weight = c(-1.7, 0, 0.6, 0.6, -0.7, -0.3, -0.6, 
-1, -1, 2, 0.1, -0.6, -1.5, 2, -0.7, -0.2, -0.9, -0.6, 1.1, -2, 
1.4, -1, -1.1, 0.5, 1.3, 0, -0.5, -3, 1.1, -0.6), steps = c(19217, 
15758, 14124, 14407, 5565, 20860, 17536, 17156, 17219, 652, 1361, 
8524, 1169, 3117, 3135, 1917, 4267, 7067, 8927, 2436, 3014, 5281, 
8104, 6836, 8939, 4923, 6885, 10581, 10370, 11024), calories = c(1943, 
1581, 1963, 1551, 1699, 1789, 1550, 2036, 1707, 1522, 1672, 1994, 
1588, 1506, 1678, 1673, 1662, 1906, 1814, 1609, 1799, 1825, 1654, 
2291, 1788, 2019, 1911, 1589, 2177, 2137)), class = c("tbl_df", 
"tbl", "data.frame"), row.names = c(NA, -30L)) %>% 
  as_tibble(.)

#lm fit
lmmod_simp <- lm(weight ~  steps * calories, data = test_df)

#tidymodels
linear_reg_lm_spec <-
  linear_reg() %>%
  set_engine('lm')

basic_rec <-  recipe(weight ~ steps  + calories, test_df) %>% 
  step_interact(terms = ~ steps:calories) 

lm_wflw <- workflow() %>% 
  add_recipe(basic_rec) %>% 
  add_model(linear_reg_lm_spec) 

lm_fit <- fit(lm_wflw, data = test_df)

lm_fit_extracted <- lm_fit %>% extract_fit_parsnip() 

当我查看输出时,两者都具有相同的系数

lmmod_simp

lm_fit_extracted

但是当我去预测时,预测完全不同

ggemmeans(lmmod_simp, terms = c("steps", "calories[1500,2000,2500]")) %>%
  as.data.frame() %>%
  ggplot(aes(x,predicted, color=group, linetype = group))+
  geom_line()

模型 1

ggemmeans(lm_fit_extracted, terms = c("steps", "calories[1500,2000,2500]")) %>%
  as.data.frame() %>%
  ggplot(aes(x,predicted, color=group, linetype = group))+
  geom_line()

模组lm2

也许我不能/不应该以这种方式使用 parsnip fit 对象,但这似乎很奇怪,因为它们显示了相同的系数。

我很感激任何帮助!

4

1 回答 1

1

你得到不同的结果,因为lmmod_simplm_fit_extracted是不同的模型。虽然lm_fit对步骤有交互影响,lm_fit_extracted但不知道此交互,因为它在执行交互计算后获取数据。

如果您打算将模型用于诊断以外的其他用途,通常不建议从工作流对象中提取模型。

于 2021-12-12T06:55:29.550 回答