Nadd
Nadd

Reputation: 136

How can I load a .csv file in java code to test with weka?

I have a model obtained from weka classifier and I want to test it in java code, But when I read instances, an error appear:

Exception in thread "main" java.io.IOException: keyword @relation expected, read Token[Word], line 1
at weka.core.Instances.errms(Instances.java:1863)
at weka.core.Instances.readHeader(Instances.java:1740)
at weka.core.Instances.<init>(Instances.java:119)
at licenta1.LoadModelWeka.main(LoadModelWeka.java:18)

My code is:

package licenta1;

import weka.core.Instances;
import weka.classifiers.bayes.NaiveBayes;
import weka.classifiers.trees.J48;
import weka.classifiers.Evaluation;

import java.util.Random;
import java.io.BufferedReader;
import java.io.FileReader ;

public class LoadModelWeka
{
   public static void main(String[] args) throws Exception {
   // training
      BufferedReader reader = null;
      reader=new BufferedReader(new FileReader("D:\\aaaaaaaaaaaaaaaaaaaaaa\\Licenta\\BioArtLicTrainSetTask1.csv"));
      Instances train =new Instances (reader);
      train.setClassIndex(0);     
      reader.close();

      NaiveBayes nb = new NaiveBayes();
      nb.buildClassifier(train);
      Evaluation eval = new Evaluation(train);
      eval.crossValidateModel(nb, train, 10 , new Random(1));

      System.out.println(eval.toSummaryString("\n Results \n=====\n",true));
      System.out.println(eval.fMeasure(1)+" "+eval.precision(1)+" "+eval.recall(1)+" ");           
   }   
}

Can somebody help me? Mt training set is in .csv format

Upvotes: 1

Views: 1860

Answers (3)

Mattyas yahya
Mattyas yahya

Reputation: 53

im using weka jar 3.7.10, and this is how i can load csv using weka :

   DataSource source1 = new DataSource("D:\\aaaaaaaaaaaaaaaaaaaaaa\\Licenta\\BioArtLicTrainSetTask1.csv");
        Instances pred_test = source1.getDataSet();

Upvotes: 1

prathamesh patil
prathamesh patil

Reputation: 21

This snippet is useful to directly load csv content and convert them to Instances. Usually .arff is used for weka operations and this loader directly converts csv files to arff internally and then to Instances class.

 CSVLoader loader = new CSVLoader();
 loader.setSource(new File("filename.csv"));
 Instances trainingDataSet = loader.getDataSet();

Upvotes: 2

Batman Rises
Batman Rises

Reputation: 349

Instead of using Buffered Reader you can try

DataSource source = new DataSource("/some/where/data.arff");

For more information visit this link http://weka.wikispaces.com/Use+WEKA+in+your+Java+code

Upvotes: 1

Related Questions