Tree visualization (Intermediate)

Decision trees can be extremely helpful to understand the underlying patterns in the dataset when visualized. This recipe demonstrates how to visualize a J48 decision tree. We will load our Titanic dataset, build a tree, and visualize it in a frame.

How to do it...

To visualize a tree, run this snippet:

import java.awt.BorderLayout;
import java.io.BufferedReader;
import java.io.FileReader;

import weka.classifiers.trees.J48;
import weka.core.Instances;
import weka.gui.treevisualizer.PlaceNode2;
import weka.gui.treevisualizer.TreeVisualizer;

...
Instances data = new Instances(new BufferedReader(new FileReader(dataset)));
data.setClassIndex(data.numAttributes() - 1);

J48 classifier = new J48();
classifier.buildClassifier(data);


TreeVisualizer tv = new TreeVisualizer(null, classifier.graph(), new PlaceNode2());

JFrame frame = new javax.swing.JFrame("Tree Visualizer");
frame.setSize(800, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.getContentPane().add(tv);
frame.setVisible(true);

tv.fitToScreen();

How it works...

Import the J48 classifier and the weka.core.Instances class:

import weka.classifiers.trees.J48;
import weka.core.Instances;

From weka.gui.treevisualizer first import the PlaceNode2 class that places the nodes of a tree so that they fall evenly below their parent without overlapping.

import weka.gui.treevisualizer.PlaceNode2;

Next, from the same package, import TreeVisualizer, which displays the node structure in Swing:

import weka.gui.treevisualizer.TreeVisualizer;

Then, load a dataset:

Instances data = new Instances(new BufferedReader(new FileReader(dataset)));
data.setClassIndex(data.numAttributes() - 1);

Build a classifier:

J48 classifier = new J48();
classifier.buildClassifier(data);

Call the TreeVisualizer(TreeDisplayListener tdl, String dot, NodePlace p) constructor. It expects a listener (null in our case), a tree provided in dot format (generated by classifier.graph()), and an algorithm to place the nodes (PlaceNode2):

TreeVisualizer tv = new TreeVisualizer(null, classifier.graph(), new PlaceNode2());

Create a frame:

JFrame frame = new javax.swing.JFrame("Tree Visualizer");
frame.setSize(800, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Add tree visualizer to the content pane:

frame.getContentPane().add(tv);

Make the frame visible:

frame.setVisible(true);

And call the fitToScreen() method to resize the tree:

tv.fitToScreen();

The result is a frame:

How it works...
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.83.199