I've fitted a logistic regression model that predicts the a binary outcome vs
from mpg
(mtcars
dataset). The plot is shown below. How can I determine the mpg
value for any particular vs
value? For example, I'm interested in finding out what the mpg
value is when the probability of vs
is 0.50. Appreciate any help anyone can provide!
model <- glm(vs ~ mpg, data = mtcars, family = binomial)
ggplot(mtcars, aes(mpg, vs)) +
geom_point() +
stat_smooth(method = "glm", method.args = list(family = "binomial"), se = FALSE)
Calculating predictions manually The equation for this model in terms of the log odds was: logit(E(SmokeNow))=2.60651−0.05423×Age. logit(E(SmokeNow))=2.60651−0.05423×30=0.97961. Since the odds are more interpretable than the log odds, we can convert our log odds prediction to the odds scale.
The predict() function can be used to predict the probability that the market will go up, given values of the predictors. The type="response" option tells R to output probabilities of the form P(Y = 1|X) , as opposed to other information such as the logit .
Logistic regression is a classification algorithm. It is used to predict a binary outcome based on a set of independent variables.
The easiest way to calculate predicted values from your model is with the predict()
function. Then you can use a numerical solver to find particular intercepts. For example
findInt <- function(model, value) {
function(x) {
predict(model, data.frame(mpg=x), type="response") - value
}
}
uniroot(findInt(model, .5), range(mtcars$mpg))$root
# [1] 20.52229
Here findInt
just takes the model and a particular target value and returns a function that uniroot
can solve for 0 to find your solution.
You can solve for mpg
directly as follows:
mpg = (log(p/(1-p)) - coef(model)[1])/coef(model)[2]
Detailed explanation:
When you fit the regression model, the equation you are fitting is the following:
log(p/(1-p)) = a + b*mpg
Where p
is the probability that vs
=1, a
is the intercept and b
is the coefficient of mpg
. From the model fit results (just type model
or summary(model)
) we see that a = -8.8331 and b = 0.4304. We want to find mpg
when p
=0.5. So, the equation we need to solve is:
log(0.5/(1-0.5)) = -8.331 + 0.4304*mpg
log(1) = 0 = -8.331 + 0.4303*mpg
Rearranging,
mpg = 8.8331/0.4304 = 20.523
In general, to solve for mpg
for any value of p
:
mpg = (log(p/(1-p)) + 8.8331)/0.4304
Or, to make it more easily reproducible:
mpg = (log(p/(1-p)) - coef(model)[1])/coef(model)[2]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With