USING NEURAL NETWORKS IN JAVA CODE

Neural networks trained and saved with easyNeurons can be easily used in your Java programs. You just need to import the Neuroph Library neuroph.jar which is part of this distribution and do the following:

import org.neuroph.core.NeuralNetwork;
import java.util.Vector;

/**
* This example shows how to load and use neural network created and saved with easyNeurons
*/
public class UseNeuralNetworkDemo {

public static void main(String[] args) {

// load neural network
NeuralNetwork myNeuralNetwork = NeuralNetwork.load("mySamplePerceptron.nnet");
// set network input
myNeuralNetwork.setInput(1, 1);
// calculate network
myNeuralNetwork.calculate();
// get network output
double[] networkOutput = myNeuralNetwork.getOutput();

}

}

 

Also you can create, train and save neural network in Java code like this:

package org.neuroph.samples;

import org.neuroph.core.NeuralNetwork;
import org.neuroph.nnet.Perceptron;
import org.neuroph.core.learning.DataSet;
import org.neuroph.core.learning.DataSetRow;

/**
* This sample shows how to create, train, save and load simple Perceptron neural network
*/
public class PerceptronSample {

public static void main(String args[]) {

// create training set (logical AND function)
DataSet trainingSet = new DataSet(2, 1);
trainingSet.addRow(new DataSetRow(new double[]{0, 0}, new double[]{0}));
trainingSet.addRow(new DataSetRow(new double[]{0, 1}, new double[]{0}));
trainingSet.addRow(new DataSetRow(new double[]{1, 0}, new double[]{0}));
trainingSet.addRow(new DataSetRow(new double[]{1, 1}, new double[]{1}));

// create perceptron neural network
NeuralNetwork myPerceptron = new Perceptron(2, 1);

// learn the training set
myPerceptron.learn(trainingSet);

// test perceptron
System.out.println("Testing trained perceptron");
testNeuralNetwork(myPerceptron, trainingSet);

// save trained perceptron
myPerceptron.save("mySamplePerceptron.nnet");

// load saved neural network
NeuralNetwork loadedPerceptron = NeuralNetwork.load("mySamplePerceptron.nnet");

// test loaded neural network
System.out.println("Testing loaded perceptron");
testNeuralNetwork(loadedPerceptron, trainingSet);

}

public static void testNeuralNetwork(NeuralNetwork nnet, DataSet testSet) {

for(DataSetRow dataRow : testSet.getRows()) {
      nnet.setInput(dataRow.getInput());
     nnet.calculate();
     double[] networkOutput = nnet.getOutput();
     System.out.print("Input: " + Arrays.toString(dataRow.getInput()));
     System.out.println(" Output: " + Arrays.toString(networkOutput));
}

}

}

For more examples see org.neuroph.samples package.