首页 > 解决方案 > 在 R 中绘制 LASSO 模型的交互效果

问题描述

我用交互项拟合了一个套索逻辑模型。然后我想使用交互图来可视化这些交互。我试图找到一些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>

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

谢谢

标签: rplotinteractionglmnetlasso-regression

解决方案


predict.glmnetnewx必须是一个矩阵。你需要自己赋予交互价值。

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) 

推荐阅读