Caret 中的逻辑回归 - 没有拦截?

Logistic Regression in Caret - No Intercept?

使用 caret 包在 R 中执行逻辑回归并尝试强制零截距,使得 x=0 处的概率为 .5。在其他形式的回归中,您似乎可以使用 tunegrid 关闭截距,但它没有逻辑回归的功能。有什么想法吗?

model <- train(y ~ 0+ x, data = data, method = "glm", family = binomial(link="probit"),
               trControl = train.control)

是的,我 "know" x=0 的概率应该是 .5,因此试图强制它。

vignette 关于如何为插入符号设置自定义模型。所以在下面的解决方案中,你也可以看到为什么拦截持续存在:

library(caret)
glm_wo_intercept = getModelInfo("glm",regex=FALSE)[[1]]

如果你看合身度,有一行:

glm_wo_intercept$fit

....
modelArgs <- c(list(formula = as.formula(".outcome ~ ."), data = dat), theDots)
...

所以拦截器是默认存在的。您可以在此修改后的模型上更改此行和 运行 插入符号:

glm_wo_intercept$fit = function(x, y, wts, param, lev, last, classProbs, ...) {
  dat <- if(is.data.frame(x)) x else as.data.frame(x)
  dat$.outcome <- y
  if(length(levels(y)) > 2) stop("glm models can only use 2-class outcomes")

  theDots <- list(...)
  if(!any(names(theDots) == "family"))
        {
    theDots$family <- if(is.factor(y)) binomial() else gaussian()
                    }
  if(!is.null(wts)) theDots$weights <- wts
  # change the model here
  modelArgs <- c(list(formula = as.formula(".outcome ~ 0+."), data = dat), theDots)

  out <- do.call("glm", modelArgs)
  out$call <- NULL
  out
                  }

我们拟合模型:

data = data.frame(y=factor(runif(100)>0.5),x=rnorm(100))
model <- train(y ~ 0+ x, data = data, method = glm_wo_intercept, 
family = binomial(),trControl = trainControl(method = "cv",number=3))

predict(model,data.frame(x=0),type="prob")
  FALSE TRUE
1   0.5  0.5