如何使用 r 中的 coefplot() 从 glmnet 多项式对象绘制系数?

问题描述 投票:0回答:1

我正在尝试使用 coefplot 可视化由 glmnet 多项式模型生成的系数估计。我知道,至少,Stata中coefplot的实现支持绘制多项模型系数。但是,我无法找到有关在 R 中使用 coefplot 包达到相同效果的指导。

这是我用来创建 glmnet 多项式对象并尝试 coefplot 的程序:

library(glmnet)
library(coefplot)
library(ISLR2)
 
NonameAuto<-Auto[,-9]

x<-model.matrix(origin~., NonameAuto)[,-1]
y<-NonameAuto$origin

ridge1<-glmnet(x[srand,],y[srand],family="multinomial",alpha=0)

err3<-cv.glmnet(x[srand,],y[srand],alpha=0, family="multinomial")

pred2<-predict(ridge1, type="class", s=err3$lambda.min,
               newx=x[-srand,])

err4<-mean(pred2==y[-srand])

ridge2<-glmnet(x, y, family="multinomial", alpha=0)
coefs1<-predict(ridge2, type="coefficients", s=err3$lambda.min)

coefplot(ridge2, lambda=err3$lambda.min, sort="magnitude")

调用 coefplot 然后会产生以下错误:

Error in `[.data.frame`(coefDF, theCoef != 0, ) : 
  'list' object cannot be coerced to type 'double'

据我所知,这个错误是由于在多项式对象上调用它而导致的,该对象将其系数存储为数据帧(列表),从而使其无法强制 coefs 加倍?

我应该如何在不引发错误的情况下绘制该对象的系数?

r dataframe glmnet mlogit coefplot
1个回答
0
投票

我不确定我是否理解你想要绘制的图应该是什么样子。但这有效吗:

library(ggplot2)

# Extract coefficients
coefs <- coef(ridge2, s = err3$lambda.min)

# Convert to data frame
coefs_df <- do.call(rbind, lapply(seq_along(coefs), function(i) {
  # Convert to TsparseMatrix
  coefs_t <- as(coefs[[i]], "TsparseMatrix")
  
  # Create data frame
  data.frame(Class = names(coefs)[i], 
             Row = coefs_t@i + 1, 
             Column = coefs_t@j + 1, 
             Value = coefs_t@x)
}))


ggplot(coefs_df, aes(x = Row, y = Value)) +
  geom_point() +
  geom_errorbarh(aes(xmin = Value - 0.1, xmax = Value + 0.1), height = 0.2) +
  facet_wrap(~ Class, scales = "free_y") +
  theme_bw()
© www.soinside.com 2019 - 2024. All rights reserved.