r - Getting glmnet coefficients at 'best' lambda -
i using following code glmnet:
> library(glmnet) > fit = glmnet(as.matrix(mtcars[-1]), mtcars[,1]) > plot(fit, xvar='lambda')
however, want print out coefficients @ best lambda, done in ridge regression. see following structure of fit:
> str(fit) list of 12 $ a0 : named num [1:79] 20.1 21.6 23.2 24.7 26 ... ..- attr(*, "names")= chr [1:79] "s0" "s1" "s2" "s3" ... $ beta :formal class 'dgcmatrix' [package "matrix"] 6 slots .. ..@ : int [1:561] 0 4 0 4 0 4 0 4 0 4 ... .. ..@ p : int [1:80] 0 0 2 4 6 8 10 12 14 16 ... .. ..@ dim : int [1:2] 10 79 .. ..@ dimnames:list of 2 .. .. ..$ : chr [1:10] "cyl" "disp" "hp" "drat" ... .. .. ..$ : chr [1:79] "s0" "s1" "s2" "s3" ... .. ..@ x : num [1:561] -0.0119 -0.4578 -0.1448 -0.7006 -0.2659 ... .. ..@ factors : list() $ df : int [1:79] 0 2 2 2 2 2 2 2 2 3 ... $ dim : int [1:2] 10 79 $ lambda : num [1:79] 5.15 4.69 4.27 3.89 3.55 ... $ dev.ratio: num [1:79] 0 0.129 0.248 0.347 0.429 ... $ nulldev : num 1126 $ npasses : int 1226 $ jerr : int 0 $ offset : logi false $ call : language glmnet(x = as.matrix(mtcars[-1]), y = mtcars[, 1]) $ nobs : int 32 - attr(*, "class")= chr [1:2] "elnet" "glmnet"
but not able best lambda , corresponding coefficients. help.
try this:
fit = glmnet(as.matrix(mtcars[-1]), mtcars[,1], lambda=cv.glmnet(as.matrix(mtcars[-1]), mtcars[,1])$lambda.1se) coef(fit)
or can specify specify lambda value in coef
:
fit = glmnet(as.matrix(mtcars[-1]), mtcars[,1]) coef(fit, s = cv.glmnet(as.matrix(mtcars[-1]), mtcars[,1])$lambda.1se)
you need pick "best" lambda, , lambda.1se
reasonable, or justifiable, 1 pick. use cv.glmnet(as.matrix(mtcars[-1]), mtcars[,1])$lambda.min
or other value of lambda settle upon "best" you.
Comments
Post a Comment