# Select some columns form mtcars.
input <- mtcars[,c("am","cyl","hp","wt")]
print(head(input))
lr_model = glm(formula = am ~ cyl + hp + wt, data = input, family = binomial) #binomial
print(summary(lr_model))
test_prob = predict(object = lr_model,newdata = input,type = 'response')
test_prob
glm.pred = ifelse(test_prob > 0.5, "1", "0")
table(glm.pred,input$am)
## training accuracy
mean(glm.pred == input$am)
## plot ROC curve
library(ROCR)
p <- predict(lr_model, newdata=input, type="response")
pr <- prediction(p, input$am)
prf <- performance(pr, measure = "tpr", x.measure = "fpr")
plot(prf,main = "ROC curve",lwd = 2,col = "red")
library(pROC)
auc = auc(response = input$am,predictor = p)
text(0.8,0.2,labels = paste0("AUC = ",round(auc,4)))
Multinomial logistic regression can be implemented with mlogit() from mlogit package and multinom() from nnet package. We will use the latter for this example.
cmcData <- read.csv("http://archive.ics.uci.edu/ml/machine-learning-databases/cmc/cmc.data", stringsAsFactors=FALSE, header=F)
colnames(cmcData) <- c("wife_age", "wife_edu", "hus_edu", "num_child", "wife_rel", "wife_work", "hus_occu", "sil", "media_exp", "cmc")
head(cmcData)
# Prepare Training and Test Data
set.seed(100)
trainingRows <- sample(1:nrow(cmcData), 0.7*nrow(cmcData))
training <- cmcData[trainingRows, ]
test <- cmcData[-trainingRows, ]
library(nnet)
multinomModel <- multinom(cmc ~ ., data=training) # multinom Model
summary (multinomModel) # model summary
predicted_scores <- predict (multinomModel, test, "probs") # predict on new data
predicted_class <- predict (multinomModel, test)
table(predicted_class, test$cmc)
# model accuracy
mean(predicted_class == test$cmc)