R中引导库的cv.glm中的成本函数

use*_*652 5 r glm cross-validation

我正在尝试使用R中引导库中的交叉验证cv.glm函数来确定应用glm逻辑回归时的错误分类数.

该函数具有以下签名:

cv.glm(data, glmfit, cost, K)
Run Code Online (Sandbox Code Playgroud)

前两个表示数据和模型,K表示k倍.我的问题是成本参数,定义为:

cost:两个向量参数的函数,指定交叉验证的成本函数.成本的第一个参数应该对应于观察到的响应,第二个参数应该对应于来自广义线性模型的预测或拟合响应.成本必须返回非负标量值.默认值是平均误差函数.

我想对于分类,有一个返回错误分类率的函数是有意义的:

nrow(subset(data, (predict >= 0.5  & data$response == "no") | 
                  (predict <  0.5  & data$response == "yes")))
Run Code Online (Sandbox Code Playgroud)

这当然在语法上都不正确.

不幸的是,我有限的R知识让我浪费了几个小时,我想知道是否有人可以指出我正确的方向.

Jos*_*ien 8

听起来你可能只使用cost在"示例"部分中进一步定义的成本函数(即命名的函数)?cv.glm.引用该部分:

 # [...] Since the response is a binary variable an
 # appropriate cost function is
 cost <- function(r, pi = 0) mean(abs(r-pi) > 0.5)
Run Code Online (Sandbox Code Playgroud)

这基本上是你试图用你的例子做的.与更换你的"不"和"是" 01,可以说你有两个载体,predictresponse.然后cost()很好地设计采取它们并返回平均分类率:

## Simulate some reasonable data
set.seed(1)
predict <- seq(0.1, 0.9, by=0.1)
response <-  rbinom(n=length(predict), prob=predict, size=1)
response
# [1] 0 0 0 1 0 0 0 1 1

## Demonstrate the function 'cost()' in action
cost(response, predict)
# [1] 0.3333333  ## Which is right, as 3/9 elements (4, 6, & 7) are misclassified
                 ## (assuming you use 0.5 as the cutoff for your predictions).
Run Code Online (Sandbox Code Playgroud)

我猜这个最棘手的一点就是让你的思想完全围绕着将一个函数作为参数传递的想法.(至少对我来说,这是最长的时间,使用启动包最困难的部分,这需要在相当多的地方移动.)


在2016-03-22添加:

cost()上面给出的函数在我看来是不必要的混淆; 以下替代方案完全相同,但以更具表现力的方式:

cost <- function(r, pi = 0) { 
        mean((pi < 0.5) & r==1 | (pi > 0.5) & r==0)
}
Run Code Online (Sandbox Code Playgroud)