简体   繁体   中英

How to loop glm

I want to loop ridge & lasso for 100 times to get 100 mse and mspe. My final goal is draw a boxplot to compare those 100 values. I made one regression model but I don't know how to repeat this model. How could I get the values and boxplots?

You can try the following:

ntimes <- 100

res <- replicate(ntimes, {
  cv.rr <- cv.glmnet(x=as.matrix(train[,-1]),y=as.numeric(train[,1]),alpha=0,nfolds=10,nlambda=100, intercept=FALSE)
  
  lambda.rr=cv.rr$lambda.min      
  mse.rr <- mean((coef(cv.rr)[-1] - betas.true)^2)    
  yhat.rr <- predict(cv.rr,s="lambda.min",newx=as.matrix(test[,-1]))
  mspe.rr <- mean((test[,1]-yhat.rr)^2)
  
  list(mse=mse.rr, mspe=mspe.rr)  
})

library(tidyverse)
res_df <- as.data.frame(apply(res, 1, function(x) unlist(x)))
names(res_df) <- c('mse', 'mspe')
res_df %>% gather(key='metric', value='value') %>% ggplot(aes(value, fill=metric)) + geom_boxplot()

to obtain a visualization like the following:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM