Wednesday, June 28, 2017

Naive Bayes Classifier in Java


Package provides java implementation of naive bayes classifier (NBC)
Build Status Coverage Status


  • Handle both numerical and categorical inputs


Add the following dependency to your POM file


To train the NBC:;
To use NBC for classification:
String predicted = nbc.classify(dataRow);
The trainingData object is an instance of data frame consisting of data rows (Please refers to this link to find out how to store data into a data frame)
The sample code below shows how to use NBC to solves the classification problem "heart_scale".
InputStream inputStream = new FileInputStream("heart_scale");

DataFrame dataFrame = DataQuery.libsvm().from(inputStream).build();

for(int i=0; i < dataFrame.rowCount(); ++i){
 DataRow row = dataFrame.row(i);
 row.setCategoricalTargetCell("category-label", "" +;

NBC svc = new NBC();;

for(int i = 0; i < dataFrame.rowCount(); ++i){
 DataRow row = dataFrame.row(i);
 String predicted_label = svc.classify(row);
 System.out.println("predicted: "+predicted_label+"\texpected: "+row.categoricalTarget());

No comments:

Post a Comment