Java examples for Machine Learning AI:weka
Using classifiers Vote filter
import weka.attributeSelection.BestFirst; import weka.attributeSelection.CfsSubsetEval; import weka.classifiers.Evaluation; import weka.classifiers.meta.CVParameterSelection; import weka.classifiers.meta.Vote; import weka.core.Instances; import weka.core.Utils; import weka.filters.Filter; import weka.filters.supervised.attribute.AttributeSelection; import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.PrintWriter; public class VotingWithFilter { public static void main(String[] args) throws Exception { Instances train = new Instances(new BufferedReader(new FileReader( "spambase_train.arff"))); Instances test = new Instances(new BufferedReader(new FileReader( "spambase_test.arff"))); train.setClassIndex(train.numAttributes() - 1); test.setClassIndex(test.numAttributes() - 1); //set up filter of the data AttributeSelection filter = new AttributeSelection(); BestFirst search = new BestFirst(); search.setOptions(weka.core.Utils.splitOptions("-D 2 -N 10")); filter.setEvaluator(new CfsSubsetEval()); filter.setSearch(search);//from w w w . j av a2 s . c o m filter.setInputFormat(train); Instances newtrain = Filter.useFilter(train, filter); Instances newtest = Filter.useFilter(test, filter); newtrain.setClassIndex(newtrain.numAttributes() - 1); newtest.setClassIndex(newtest.numAttributes() - 1); Vote vs = new Vote(); vs.setOptions(weka.core.Utils .splitOptions("-B \"weka.classifiers.functions.SMO\" -B \"weka.classifiers.trees.LMT\" -B \"weka.classifiers.trees.RandomForest -I 10 -K 0\" -R AVG")); System.out.println(Utils.joinOptions(vs.getOptions())); vs.buildClassifier(newtrain); PrintWriter pw = new PrintWriter(new FileWriter( "spambase-L5.txt")); for (int i = 0; i < newtest.numInstances(); i++) { double pred = vs.classifyInstance(newtest.instance(i)); pw.println(pred); } pw.close(); } }