Fit a no-intercept model in caret

守給你的承諾、 提交于 2019-12-03 05:28:12

As discussed in a linked SO question https://stackoverflow.com/a/41731117/7613376, this works in caret v6.0.76 (And the trace answer above no longer seems to work with code refactoring in caret):

caret_lmFit <- train(Sepal.Length~0+Petal.Length+Petal.Width, data=iris, "lm", 
           tuneGrid  = expand.grid(intercept = FALSE))

> caret_lmFit$finalModel

Call:
lm(formula = .outcome ~ 0 + ., data = dat)

Coefficients:
Petal.Length   Petal.Width  
       2.856        -4.479  

@rcs already told you which line in which function you need to change.

Just use trace to modify that function:

trace(caret::createModel, 
       quote(modFormula <- as.formula(".outcome ~ .-1")), at=5, print=FALSE)
caret_lmFit <- train(Sepal.Length~0+Petal.Length+Petal.Width, data=iris, "lm")
round(coef(caret_lmFit$finalModel),2)
#Petal.Length  Petal.Width 
#        2.86        -4.48 
untrace(caret::createModel)

However, I don't use caret. There might be unforeseen consequences. It's also often not a good idea to exclude the intercept from the model.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!