Search code examples
rmachine-learningglmnetcoefficients

How to see which coefficients are not 0 in cv.glmnet


I did a lasso regression by using the glm.net package. I chosed my lambda via cross validation and have now the information that the optimal model has only 6 coefficients that are not zero.

How can i see which coefficients that exactly are ?


Solution

  • Since you don't provide any sample data here is a minimal example:

    1. Generate some sample data

      set.seed(2017);
      x1 <- seq(1:100);
      x2 <- 2 * x1;
      y <- 3 * x1 + 6 * x2 + rnorm(100);
      
    2. Fit the model using CV

      fit <- cv.glmnet(cbind(x1, x2), y);
      
    3. Then coef(fit) gives the parameter estimates for different lambda values. We can extract parameter estimates for the lambda value that results in the smallest CV error with

      coef(fit, s = "lambda.min")
      #3 x 1 sparse Matrix of class "dgCMatrix"
      #                       1
      #(Intercept) 2.439590e+01
      #x1          1.451704e+01
      #x2          5.723395e-16