在 R 中绘制 LASSO 模型的交互作用

plotting interaction effects for LASSO models in R

我用交互项拟合了套索逻辑模型。然后我想使用交互图可视化这些交互。 我试图找到一些 R 函数来绘制 glmnet 模型的交互,但我找不到任何 .

是否有任何 R 包可以绘制 LASSO 的相互作用?

因为我找不到任何东西,所以我尝试通过绘制预测值来手动完成。但我收到了一些错误。

我的代码如下,

 require(ISLR)
    require(glmnet)
    y <- Smarket$Direction
    x <- model.matrix(Direction ~ Lag1 + Lag4* Volume, Smarket)[, -1]

    lasso.mod <- cv.glmnet(x, y, alpha=1,family="binomial",nfolds = 5, type.measure="class",
                           lambda = seq(0.001,0.1,by = 0.001))

     lasso.mod$lambda.min

     pred = expand.grid(Lag1 = median(Smarket$Lag1),
                            Lag4 = c(-0.64,0.0385,0.596750),
                            Volume = seq(min(Smarket$Volume), max(Smarket$Volume), length=100)) 





      lasso.mod1 <- glmnet(x, y, alpha=1,family="binomial",
                            lambda = lasso.mod$lambda.min)

     pred$Direction = predict(lasso.mod1, newx=pred, 
type="response", s= lasso.mod$lambda.min) 

我收到这个错误:

Error in cbind2(1, newx) %*% nbeta : 
  not-yet-implemented method for <data.frame> %*% <dgCMatrix>

有什么建议可以解决这个问题吗?

谢谢

predict.glmnet 表示 newx 必须是矩阵。而你需要自己赋予交互价值。

library(dplyr)

pred = expand.grid(Lag1 = median(Smarket$Lag1),
                   Lag4 = c(-0.64,0.0385,0.596750),
                   Volume = seq(min(Smarket$Volume), max(Smarket$Volume), length=100))  %>% 
  mutate(`Lag4:Volume` = Lag4 * Volume)     # preparing interaction values


pred$Direction = predict(lasso.mod1, newx = as.matrix(pred),   # convert to matrix
                         type = "link", s= lasso.mod$lambda.min) 

[编辑]
哦,我忽略了更通用,更好的方法。

pred = expand.grid(Lag1 = median(Smarket$Lag1),
                   Lag4 = c(-0.64,0.0385,0.596750),
                   Volume = seq(min(Smarket$Volume), max(Smarket$Volume), length=100)) 

pred$Direction = predict(lasso.mod1, 
                         newx = model.matrix( ~ Lag1 + Lag4* Volume, pred)[, -1], 
                         type="response", s= lasso.mod$lambda.min)