[R] Obtaining predicted probabilities for Logistic regression
Rui Barradas
ru|pb@rr@d@@ @end|ng |rom @@po@pt
Sat Jul 13 15:16:21 CEST 2024
Às 12:13 de 13/07/2024, Christofer Bogaso escreveu:
> Hi,
>
> I ran below code
>
> Dat = read.csv('https://raw.githubusercontent.com/sam16tyagi/Machine-Learning-techniques-in-python/master/logistic%20regression%20dataset-Social_Network_Ads.csv')
> head(Dat)
> Model = glm(Purchased ~ Gender, data = Dat, family = binomial())
> head(predict(Model, type="response"))
> My_Predict = 1/(1+exp(-1 * (as.vector(coef(Model))[1] *
> as.vector(coef(Model))[2] * ifelse(Dat['Gender'] == "Male", 1, 0))))
> head(My_Predict)
>
> However, My_Predict and predict(Model, type="response")) are differing
> when I tried to manually calculate prediction.
>
> Could you please help to identify what was the mistake I made?
>
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
Hello,
Sometimes when there is an error, the best way to correct it is to
rewrite the offending part of the code.
In your case, after as.vector(coef(Model))[1] you should have a plus sign.
Dat =
read.csv('https://raw.githubusercontent.com/sam16tyagi/Machine-Learning-techniques-in-python/master/logistic%20regression%20dataset-Social_Network_Ads.csv')
head(Dat)
Model = glm(Purchased ~ Gender, data = Dat, family = binomial())
# use matrix algebra
x <- cbind(1, (Dat$Gender == "Male")) %*% coef(Model)
pred1 <- exp(x)/(1 + exp(x))
# use the fitted line equation
y <- coef(Model)[1L] + coef(Model)[2L] * (Dat$Gender == "Male")
pred2 <- exp(y)/(1 + exp(y))
head(predict(Model, type="response"))
head(pred1) |> c()
head(pred2)
Hope this helps,
Rui Barradas
--
Este e-mail foi analisado pelo software antivírus AVG para verificar a presença de vírus.
www.avg.com
More information about the R-help
mailing list