简体   繁体   中英

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

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();

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

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM