为glm模型列表应用功能 [英] apply function for for list of glm models
本文介绍了为glm模型列表应用功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
您好,有谁能帮我写一个for循环或应用函数来为多个模型运行以下代码
Hi can any one write help me write a for loop or apply function to run the below code for multiple models
模拟数据
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)
拆分数据以训练和测试集
Splitting Data to train and test sets
dt = sort(sample(nrow(df), nrow(df)*.5, replace = F))
trainset=df[dt,]; testset=df[-dt,]
拟合逻辑回归模型
model1=glm( y~x1,data=trainset,family="binomial")
model2=glm( y~x1+x2,data=trainset,family="binomial")
测试和训练中的测试模型准确性
Testing Model accuracy in test and train ets
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)
推荐答案
只需将模型放在列表中
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()
可以在您的列表中使用
And sapply()
that function to your list
sapply(models, getauc)
# model1 model2
# train 0.5273818 0.5448066
# test 0.5025038 0.5146211
这篇关于为glm模型列表应用功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文