Wednesday, June 28, 2017

Naive Bayes Classifier in Java

java-naive-bayes-classifier


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

Features

  • Handle both numerical and categorical inputs

Install

Add the following dependency to your POM file
<dependency>
  <groupId>com.github.chen0040</groupId>
  <artifactId>java-naive-bayes-classifier</artifactId>
  <version>1.0.1</version>
</dependency>

Usage

To train the NBC:
nbc.fit(trainingData);
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();


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

NBC svc = new NBC();
svc.fit(dataFrame);

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