听起来你可能只使用成本函数(即名为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)
这基本上就是您在示例中尝试执行的操作。将“不”和“是”替换为0
and 1
,假设你有两个向量,predict
and response
. Then 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).
我猜最棘手的一点就是让你的思想完全围绕着将函数作为参数传递的想法。 (至少对我来说,在很长一段时间里,这是使用boot包,这需要移动相当多的地方。)
2016年3月22日添加:
功能cost()
,在我看来,上面给出的内容是不必要的混淆;下面的替代方案做了完全相同的事情,但以更具表现力的方式:
cost <- function(r, pi = 0) {
mean((pi < 0.5) & r==1 | (pi > 0.5) & r==0)
}