如何在tidymodels的recipes中仅保留模型公式的交互项
问题描述
想要创建仅包含变量交互项、不含变量主效应的模型公式,在基础R中可以通过公式里的冒号:指定交互项,但使用tidymodels的recipes包时,用step_dummy()和step_interact()处理后结果仍保留主效应,尝试remove_role()也无法解决。示例代码如下:
library(tidymodels) # 基础R中的目标模型(包含Petal.Width主效应 + 交互项,无Species主效应) basic_mod <- lm(Petal.Length ~ Petal.Width + Petal.Width:Species, data = iris) # 使用recipes的尝试,但结果仍包含Species的主效应哑变量 iris_rec <- recipe(Petal.Length ~ Petal.Width + Species, data = iris) |> step_dummy("Species") |> step_interact(~ Petal.Width:starts_with("Species")) # 查看预处理后的公式,仍有Species主效应 formula(iris_rec |> prep()) #> Petal.Length ~ Petal.Width + Species_versicolor + Species_virginica + #> Petal.Width_x_Species_versicolor + Petal.Width_x_Species_virginica #> <environment: 0x127838968> # 尝试移除Species哑变量的predictor角色,依旧无效 iris_rec |> remove_role(starts_with("Species"), old_role = "predictor") |> prep() |> formula() #> Petal.Length ~ Petal.Width + Species_versicolor + Species_virginica + #> Petal.Width_x_Species_versicolor + Petal.Width_x_Species_virginica #> <environment: 0x1106178a0>
解决方案
问题根源是remove_role()仅修改变量的角色标记,不会从数据中移除变量,而prep()后的公式会列出所有存在的变量。要彻底移除主效应,需用step_rm()直接删除对应变量:
方法1:保留Petal.Width主效应,移除Species主效应
如果目标和基础R代码一致——保留Petal.Width的主效应,仅去掉Species的主效应哑变量,可在生成交互项后添加step_rm():
iris_rec <- recipe(Petal.Length ~ Petal.Width + Species, data = iris) |> step_dummy("Species") |> step_interact(~ Petal.Width:starts_with("Species")) |> step_rm(starts_with("Species_")) # 移除Species的主效应哑变量 # 查看预处理后的公式,符合预期 formula(iris_rec |> prep()) #> Petal.Length ~ Petal.Width + Petal.Width_x_Species_versicolor + #> Petal.Width_x_Species_virginica #> <environment: 0x12345678>
方法2:完全移除所有主效应,仅保留交互项
若需要彻底去掉所有变量的主效应(包括Petal.Width),可以同时移除该变量:
iris_rec <- recipe(Petal.Length ~ Petal.Width + Species, data = iris) |> step_dummy("Species") |> step_interact(~ Petal.Width:starts_with("Species")) |> step_rm(Petal.Width, starts_with("Species_")) formula(iris_rec |> prep()) #> Petal.Length ~ Petal.Width_x_Species_versicolor + Petal.Width_x_Species_virginica #> <environment: 0x87654321>
补充说明
remove_role()的作用是变更变量角色(比如从predictor改为other),但变量仍会留在数据中,只是不被模型当作预测变量,这就是之前尝试无效的原因。step_rm()直接从数据集中删除指定变量,能彻底解决主效应残留问题。
内容的提问来源于stack exchange,提问作者Declan
相关产品推荐
相关产品推荐

