[英]Predicting new data using glm and cv.glmnet in R (including interactions and categorical variables )
[英]How to make all interactions before using glmnet
我有一個 8 列的 x 矩陣。 我想運行glmnet
進行套索回歸。 我知道我需要打電話:
glmnet(x, y, family = "binomial", ...).
但是,我如何讓x
也考慮所有單向交互? 我是否必須手動重新制作數據框:如果是這樣,有沒有更簡單的方法? 我想我希望使用 R 公式做一些事情。
是的,有一個方便的方法。 其中的兩個步驟很重要。
library(glmnet)
# Sample data
data <- data.frame(matrix(rnorm(9 * 10), ncol = 9))
names(data) <- c(paste0("x", 1:8), "y")
# First step: using .*. for all interactions
f <- as.formula(y ~ .*.)
y <- data$y
# Second step: using model.matrix to take advantage of f
x <- model.matrix(f, data)[, -1]
glmnet(x, y)
f <- as.formula( ~ .^2)
也應該適用於包括主效應和所有成對相互作用
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.