2017-10-09 36 views
-1

嗨任何一个可以写帮我写一个for循环或应用功能,运行多个模型应用功能为GLM模型的列表

下面的代码

仿真数据

set.seed(666) 
x1 = rnorm(1000) 
x2 = rnorm(1000) 
y = rbinom(1000,1,0.8) 
df = data.frame(y=as.factor(y),x1=x1,x2=x2) 

分割数据来训练组和测试组

dt = sort(sample(nrow(df), nrow(df)*.5, replace = F)) 
trainset=df[dt,]; testset=df[-dt,] 

拟合Logistic回归模型

model1=glm(y~x1,data=trainset,family="binomial") 
model2=glm(y~x1+x2,data=trainset,family="binomial") 

检验模型准确性的测试和训练ETS

我想环路列车集和测试集以上,并打印AUC安装每个模型的多个模型下面提到的代码

require(pROC) 
trainpredictions <- predict(object=model1,newdata = trainset); 
trainpredictions <- as.ordered(trainpredictions) 
testpredictions <- predict(object=model1,newdata = testset); 
testpredictions <- as.ordered(testpredictions) 
trainauc <- roc(trainset$y, trainpredictions); 
testauc <- roc(testset$y, testpredictions) 
print(trainauc$auc); print(testauc$auc) 
+0

存储在列表中的模型?您可能想要提供所有模型的子集。 – useR

+0

你想要的输出是什么?你有任何写函数的经验吗?你可以在这里使用'lapply()'。用样本输入数据帮助一个合适的[可重现的示例](https://stackoverflow.com/questions/5963269/how-to-make-a- great-r-reproducible-example)会更容易。 – MrFlick

+0

@MrFlick我编辑了这个问题并添加了一个可重现的例子; –

回答

0

刚把你的机型列表中的

models <- list(
    model1 = glm(y~x1,data=trainset,family="binomial"), 
    model2 = glm(y~x1+x2,data=trainset,family="binomial") 
) 

定义值提取功能

getauc <- function(model) { 
    trainpredictions <- predict(object=model,newdata = trainset); 
    trainpredictions <- as.ordered(trainpredictions) 
    testpredictions <- predict(object=model,newdata = testset); 
    testpredictions <- as.ordered(testpredictions) 
    trainauc <- roc(trainset$y, trainpredictions); 
    testauc <- roc(testset$y, testpredictions) 
    c(train=trainauc$auc, test=testauc$auc) 
} 

而且sapply(),其功能是您的列表

sapply(models, getauc) 
#   model1 model2 
# train 0.5273818 0.5448066 
# test 0.5025038 0.5146211