1. 程式人生 > >讀取和儲存arff檔案

讀取和儲存arff檔案

情景:

找出wake分類後預測錯誤的例項。

包:

自然是weka.jar,它存在於weka的安裝目錄下。

細節:

見weka.jar的javadoc。

程式碼:

package com.weka.test;

import java.io.File;
import java.io.IOException;

import weka.core.Attribute;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.converters.ArffLoader;
import weka.core.converters.ArffSaver;
import weka.core.converters.Saver;

public class Test {
	public static void filter(String loadPath, String savePath) throws IOException { 
		ArffLoader loader = new ArffLoader();
		loader.setFile(new File(loadPath));
		Instances structure = loader.getStructure();
		Attribute attrClass = structure.attribute("class");
		Attribute attrPredictedclass = structure.attribute("predictedclass");

		ArffSaver saver = new ArffSaver();
		saver.setFile(new File(savePath));
		saver.setRetrieval(Saver.INCREMENTAL);
		saver.setStructure(structure);

		Instance inst;
		while( (inst = loader.getNextInstance(structure)) != null ) {
			double a = inst.value(attrClass);
			double b = inst.value(attrPredictedclass);
			if(a != b) {
				saver.writeIncremental(inst);
			}
		}

		saver.writeIncremental(null);
	}
}