0
# training data set
data(x_train)
# training data label
data(y_train)

# test data set
data(x_test)
# test data label
data(y_test)

library(e1071)

#svm 
svm_model = svm(x_train,y_train)
y_pred_svm = predict(svm_model,x_test)
y_pred_svm = round(y_pred_svm)
accuracy_svm = sum(y_pred_svm==y_test)/dim(y_test)[1]

#naive bayes
bayes_model = naiveBayes(x_train,y_train)
y_pred_bayes = predict(bayes_model,x_test)
y_pred_bayes = round(y_pred_bayes)
accuracy_bayes = sum(y_pred_bayes==y_test)/dim(y_test)[1]

Labels are numbers from 1 to 5.

This code works for SVM, but not working for Naive Bayes classifier, tobe more specific, y_pred_svm is vector of numbers, but y_pred_bayes is not.

I found a lot of examples on naiveBayes function in the package, but data and label are not in separate arrays. Can anyone help me out? Thanks.

ilovecp3
  • 2,825
  • 5
  • 18
  • 19
  • have you tried 'str(y_pred_bayes)' to see how the object is structured? – screechOwl Apr 11 '15 at 21:11
  • when I type y_pred_bayes in the command window, it says: factor(0) Levels: – ilovecp3 Apr 11 '15 at 21:12
  • I found the reason, basically I use y_train=read.table("y_train.txt") to get the label data, however, it is stored as a data.frame format. I use y_train = as.factor(y_train[,1]) to transform it into factor format and the same goes for y_test, then the above code worked. – ilovecp3 Apr 11 '15 at 22:04

0 Answers0