Search code examples
rcross-validationglmnetmse

How to extract the CV errors for optimal lambda using glmnet package?


I'm using the glment package for regression in R. I do the cross validation using cv.fit<-cv.glmnet(x,y,...), and I get optimum lambda using cvfit$lambda.min. but I want to also get the corresponduing MSE(mean square error) for that lambda. would someone help me to get it ?


Solution

  • From ?cv.glmnet:

    # ...
    # Value:
    #
    #     an object of class ‘"cv.glmnet"’ is returned, which is a list with
    #     the ingredients of the cross-validation fit. 
    #
    # lambda: the values of ‘lambda’ used in the fits.
    #
    #   cvm: The mean cross-validated error - a vector of length
    #       ‘length(lambda)’.
    # ...
    

    So in your case, the cross-validated mean squared errors are in cv.fit$cvm and the corresponding lambda values are in cv.fit$lambda.

    To find the minimum MSE you can use which as follows:

    i <- which(cv.fit$lambda == cv.fit$lambda.min)
    mse.min <- cv.fit$cvm[i]
    

    or shorter

    mse.min <- cv.fit$cvm[cv.fit$lambda == cv.fit$lambda.min]