Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
375 views
in Technique[技术] by (71.8m points)

r - Fit a no-intercept model in caret

In R, I specify a model with no intercept as follows:

data(iris)
lmFit <- lm(Sepal.Length ~ 0 + Petal.Length + Petal.Width, data=iris)
> round(coef(lmFit),2)
Petal.Length  Petal.Width 
        2.86        -4.48 

However, if I fit the same model with caret, the resulting model includes an intercept:

library(caret)
caret_lmFit <- train(Sepal.Length~0+Petal.Length+Petal.Width, data=iris, "lm")
> round(coef(caret_lmFit$finalModel),2)
 (Intercept) Petal.Length  Petal.Width 
        4.19         0.54        -0.32 

How do I tell caret::train to exclude the intercept term?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

@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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...