r - 在 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>
有什么建议可以解决这个问题吗?
谢谢
解决方案
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)
推荐阅读
- git - git/jenkins TLS 问题
- python - 使用委托向 QTableView 单元格中的文本添加复选框
- python - 搜索所有“大于”的值并进行运算(减法)
- c# - 在 C# 中将传递的函数结果分配给具有变量类型的对象
- django - 如何在 Django 频道中接受 WebSocket 扩展?
- javascript - 如何在 Vue.js 2.6、Vue CLI 4、Vuetify 2.2 中计算两个项目的值
- java - 简化具有多个条件的 if 语句
- css - 防止 Material-UI Autocomplete Popper 组件被绝对定位
- pandas - TypeError:“时间戳”和“numpy.float64”的实例之间不支持“<=”
- javascript - 已弃用的 WebSpeech API 函数的替代方案