【问题标题】:How to loop glm如何循环 glm
【发布时间】:2021-11-24 15:07:05
【问题描述】:

我想循环 ridge & lasso 100 次以获得 100 mse 和 mspe。我的最终目标是绘制一个箱线图来比较这 100 个值。我做了一个回归模型,但我不知道如何重复这个模型。 我怎样才能得到值和箱线图?

【问题讨论】:

  • 我认为我的问题不完整。但我只想知道如何循环这个模型,而不是特定的代码。
  • 你的betas.true是什么?
  • betas.true=c(rep(0.5, 10),rep(0,P-10)) 和 p=50
  • 请提供足够的代码,以便其他人更好地理解或重现问题。

标签: r machine-learning glmnet


【解决方案1】:

您可以尝试以下方法:

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()

获得如下可视化:

【讨论】:

    猜你喜欢
    • 2020-09-26
    • 1970-01-01
    • 2021-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-25
    • 2012-11-21
    • 1970-01-01
    相关资源
    最近更新 更多