Using a neural network class in WEKA in Java code

Hi, I want to do simple training and testing using the Neural Network in the WEKA library.

But, I believe that this is not trivial, but its difference from the NaiveBayes class in its library.

Does anyone have an example of how to use this class in java code?

+4
source share
2 answers

The following steps may help you:

  • Add Weka Libraries

Download Weka from http://www.cs.waikato.ac.nz/ml/weka/downloading.html .

From the package, find "Weka.jar" and add it to the project.

Java code snippet

  1. Building a neural classifier

    public void simpleWekaTrain(String filepath)
    {
    try{
    //Reading training arff or csv file
    FileReader trainreader = new FileReader(filepath);
    Instances train = new Instances(trainreader);
    train.setClassIndex(train.numAttributes() – 1);
    //Instance of NN
    MultilayerPerceptron mlp = new MultilayerPerceptron();
    //Setting Parameters
    mlp.setLearningRate(0.1);
    mlp.setMomentum(0.2);
    mlp.setTrainingTime(2000);
    mlp.setHiddenLayers("3?);
    mlp.buildClassifier(train);
    }
    catch(Exception ex){
    ex.printStackTrace();
    }
    }
    

Another way to set parameters,

    mlp.setOptions(Utils.splitOptions("-L 0.1 -M 0.2 -N 2000 -V 0 -S 0 -E 20 -H 3?));

Where

L = Learning Rate
M = Momentum
N = Training Time or Epochs
H = Hidden Layers
etc.

    Evaluation eval = new Evaluation(train);
    eval.evaluateModel(mlp, train);
    System.out.println(eval.errorRate()); //Printing Training Mean root squared Error
    System.out.println(eval.toSummaryString()); //Summary of Training

K-Fold

    eval.crossValidateModel(mlp, train, kfolds, new Random(1));
  1. /

    Instances datapredict = new Instances(
    new BufferedReader(
    new FileReader(<Predictdatapath>)));
    datapredict.setClassIndex(datapredict.numAttributes() – 1);
    Instances predicteddata = new Instances(datapredict);
    //Predict Part
    for (int i = 0; i < datapredict.numInstances(); i++) {
    double clsLabel = mlp.classifyInstance(datapredict.instance(i));
    predicteddata.instance(i).setClassValue(clsLabel);
    }
    //Storing again in arff
    BufferedWriter writer = new BufferedWriter(
    new FileWriter(<Output File Path>));
    writer.write(predicteddata.toString());
    writer.newLine();
    writer.flush();
    writer.close();
    
+7

, " NeuralNetwork WEKA, NeuralNetwork, " MultilayerPerceptron "

, . , WEKA ??? T__T

, , .

http://weka.8497.n7.nabble.com/Multi-layer-perception-td2896.html

Ps. , , !

+1

All Articles