在r中的函数中应用逻辑回归



我想为多个参数运行逻辑回归,并存储不同的指标,即AUC。我写了下面的函数,但当我调用它时,我得到了一个错误:eval(predvars, data, env)中的错误:对象'X0'没有找到,即使变量存在于我的训练和测试数据集中。任何想法?

new.function <- function(a) {
model = glm(extry~a,family=binomial("logit"),data = train_df)
pred.prob <- predict(model,test_df, type='response')
predictFull <- prediction(pred.prob, test_df$extry)
auc_ROCR <- performance(predictFull, measure = "auc")
my_list <- list("AUC" =  auc_ROCR)
return(my_list) 
}
# Call the function new.function supplying 6 as an argument.
les <- new.function(X0)

函数不起作用的主要原因是您试图将对象调用到公式中。您可以使用粘贴公式功能来修复它,但这最终是相当有限的。

我建议你考虑使用update。这让你更灵活地改变多个变量组合,或改变一个训练数据集,在不破坏功能。

model = glm(extry~a,family=binomial("logit"),data = train_df)
new.model = update(model, .~X0)

new.function <- function(model){
pred.prob <- predict(model, test_df, type='response')
predictFull <- prediction(pred.prob, test_df$extry)
auc_ROCR <- performance(predictFull, measure = "auc")
my_list <- list("AUC" =  auc_ROCR)
return(my_list) 
}

les <- new.function(new.model)

函数通过调用test_df可以进一步提高作为一个单独的参数,这样你就可以把它与另一种测试数据。

要按预期的方式运行函数,需要使用非标准求值来捕获符号并将其插入公式中。这可以用match.callas.formula来完成。下面是一个使用虚拟数据的完全可复制的示例:

new.function <- function(a) {

# Convert symbol to character
a <- as.character(match.call()$a)

# Build formula from character strings
form <- as.formula(paste("extry", a, sep = "~"))

model <- glm(form, family = binomial("logit"), data = train_df)
pred.prob <- predict(model, test_df, type = 'response')
predictFull <- ROCR::prediction(pred.prob, test_df$extry)
auc_ROCR <- ROCR::performance(predictFull, "auc")
list("AUC" =  auc_ROCR)
}

现在我们可以按你想要的方式调用函数了:

new.function(X0)
#> $AUC
#> A performance instance
#>   'Area under the ROC curve'
new.function(X1)
#> $AUC
#> A performance instance
#>   'Area under the ROC curve'

如果你想看到曲线下的实际面积,你需要这样做:

new.function(X0)$AUC@y.values[[1]]
#> [1] 0.6599759

所以你可能希望修改你的函数,使列表包含auc_ROCR@y.values[[1]]而不是auc_ROCR


数据使用

set.seed(1)
train_df <- data.frame(X0 = sample(100), X1 = sample(100))
train_df$extry <- rbinom(100, 1, (train_df$X0 + train_df$X1)/200)
test_df  <- data.frame(X0 = sample(100), X1 = sample(100))
test_df$extry <- rbinom(100, 1, (test_df$X0 + test_df$X1)/200)

由reprex包(v2.0.1)创建于2022-06-29

最新更新