2015년 9월 11일 금요일

[R] Naive Bayesian Classifier

# Performance Evaluation Function ---------------------------------
perf_eval <- function(cm){
  
  # True positive rate: TPR
  TPR = cm[2,2]/sum(cm[2,])
  # True negative rate: TNR
  TNR = cm[1,1]/sum(cm[1,])
  # Simple Accuracy
  ACC = (cm[1,1]+cm[2,2])/sum(cm)
  # Balanced Correction Rate
  BCR = sqrt(TPR*TNR)
  
  return(c(TPR, TNR, ACC, BCR))
}


# Classifier 1: Naive Bayesian Classifier ---------------------------------
# e1071 package install
install.packages("e1071", dependencies = TRUE)

# Call the e1071 package
library(e1071)

ploan <- read.csv("Personal Loan.csv")

input_idx <- c(2,3,4,6,7,8,9,11,12,13,14)
target_idx <- 10

ploan_input <- ploan[,input_idx]
ploan_target <- as.factor(ploan[,target_idx])
ploan_data <- data.frame(ploan_input, ploan_target)

# Split the data into the training/validation sets
trn_idx <- sample(1:dim(ploan_data)[1], round(0.7*dim(ploan_data)[1]))
ploan_trn <- ploan_data[trn_idx,]
ploan_val <- ploan_data[-trn_idx,]

# Training the Naive Bayesian Classifier ~ left is indepen, ~ right is depen x1+X2+x3
nb_model <- naiveBayes(ploan_target ~ ., data = ploan_trn)
nb_model$apriori
nb_model$tables

# Predict the new input data based on Naive Bayesian Classifier
posterior = predict(nb_model, ploan_val, type = "raw")
nb_prey = predict(nb_model, ploan_val, type ="class")

# Generate a confusion matrix
cfmatrix <- table(ploan_val$ploan_target, nb_prey)

# Evaluate the performance
perf_mat <- matrix(0, 4, 4)

perf_mat[,1] <- perf_eval(cfmatrix)
perf_mat

댓글 없음:

댓글 쓰기