Using MOA interactively with the new Java Shell tool

The Java Shell tool (JShell) is a new interactive tool for learning the Java programming language and prototyping Java code, available in the last releases of Java. It is a Read-Evaluate-Print Loop (REPL), which evaluates declarations, statements, and expressions as they are entered and immediately shows the results.

Let’s see an example, using the Java Shell tool (JShell). First we need to start it, telling where the MOA library is:

jshell --class-path moa.jar

| Welcome to JShell -- Version 9.0.1
| For an introduction type: /help intro

Let’s run a very simple experiment: using a decision tree (Hoeffding Tree) with data generated from an artificial stream generator (RandomRBFGenerator).

We should start importing the classes that we need, and defining the stream and the learner.

jshell> import moa.classifiers.trees.HoeffdingTree
jshell> import moa.streams.generators.RandomRBFGenerator

jshell> HoeffdingTree learner = new HoeffdingTree();
jshell> RandomRBFGenerator stream = new RandomRBFGenerator();

Now, we need to initialize the stream and the classifier:

jshell> stream.prepareForUse()
jshell> learner.setModelContext(stream.getHeader())
jshell> learner.prepareForUse()

Now, let’s load an instance from the stream, and use it to train the decision tree:

jshell> import

jshell> Instance instance = stream.nextInstance().getData()
instance ==> 0.2103720255378259,1.0095862047200432,0.091900238 ... .29700709397885133,class2,

jshell> learner.trainOnInstance(instance)

And finally, let’s use it to do a prediction.

jshell> learner.getVotesForInstance(instance)
$11 ==> double[2] { 0.0, 1.0 }
jshell> learner.correctlyClassifies(instance)
$12 ==> true

As shown in this example, it is very easy to use the Java interpreter to run MOA interactively.