Search code examples
javawekanaivebayes

How can I access Weka produced Naive Bayes trees in Java?


From what I understand of the Naive Bayes Classifier, a tree is produced for each label (or possibility) based on ‘evidence’ (training sets). Using these trees predictions can be made for future examples e.g. whether an instance can be classified as either “anomaly” or “normal”.

Is there a way within the weka library for me to visually output each label tree? Or to access these trees in Java?

Thanks


Solution

  • Naive Bayes does not produce a tree, so it might be worth looking into using a classifier that does, such as J48. The tree classifiers can be found under the weka/classifiers/trees/ directory in the WEKA GUI client.

    An example of a Naive Bayes classifier is:

    enter image description here

    Whereas an example of a tree based classifier such as J48 is:

    enter image description here

    This tree can be accessed in both the WEKA GUI and using Java. If using the WEKA GUI, the tree can be visualized by right clicking the classification result and pressing Visualize tree *:

    enter image description here

    Within Java, the tree can be printed into the console by printing the classifier object itself as such:

        //Get File
        reader = new BufferedReader(new FileReader(path + "/ArffFile.arff"));
    
        //Get the data
        Instances data = new Instances(reader);
        reader.close();
    
        //Setting class attribute
        data.setClassIndex(data.numAttributes() - 1);
    
        //Make tree
        J48 tree = new J48();
        String[] options = new String[1];
        tree.buildClassifier(data);
    
        //Print tree
        System.out.println(tree);
    

    *Note that it will also be printed into the classifier output window by default.