有一个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