JLosc
JLosc

Reputation: 5

How to plot coefficients from glmnet multinomial object using coefplot() in r?

I am trying to visualise coefficient estimates, produced by a glmnet multinomial model, using coefplot. I know, at least, the implementation of coefplot in Stata supports plotting multinomial model coefficients. However, I am unable to find guidance on using the coefplot package in R to the same effect.

Here is the program I am using to create a glmnet multinomial object, and attempt a 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")

Calling coefplot then produces the following error:

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

As far as I can tell, this error results from calling it on a multinomial object which stores its coefficients as a dataframe (list), making it unable to coerce coefs to double?

How should I go about plotting coefficients from this object without invoking an error?

Upvotes: 0

Views: 73

Answers (1)

rw2
rw2

Reputation: 1793

I'm not certain I understand what the plots you're trying to make should look like. But does this work:

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()

Upvotes: 0

Related Questions