Getting predicted classes from R glmnet object

user721975 picture user721975 · Feb 18, 2012 · Viewed 7k times · Source

I am trying to build simple multi-class logistic regression models using glmnet in R. However when I try to predict the test data and obtain contingency table I get an error. A sample session is reproduced below.

> mat = matrix(1:100,nrow=10)
> test = matrix(1:50,nrow=5)

> classes <- as.factor(11:20)

> model <- glmnet(mat, classes, family="multinomial", alpha=1)
> pred <- predict(model, test)
> table(pred, as.factor(11:15))
  Error in table(pred, as.factor(11:15)) : 
  all arguments must have the same length

Any help will be appreciated. R noob here.

Thanks.

Answer

joran picture joran · Feb 19, 2012

The predict method for a glmnet object requires that you specify a value for the argument s, which indicates which values of the regularization parameter for which you want predictions.

(glmnet fits the model for several values of this regularization parameter simultaneously.)

So if you don't specify a value for s, predict.glmnet returns predictions for all the values. If you want just a single set of predictions, you need to either set a value for s when you call predict, or you need to extract the relevant column after the fact.