Java examples for Machine Learning AI:weka
performs attribute selection using CfsSubsetEval and GreedyStepwise and trains J48
import weka.attributeSelection.*; import weka.core.*; import weka.core.converters.ConverterUtils.*; import weka.classifiers.*; import weka.classifiers.meta.*; import weka.classifiers.trees.*; import weka.filters.*; import java.util.*; public class AttributeSelectionTest { protected static void useClassifier(Instances data) throws Exception { AttributeSelectedClassifier classifier = new AttributeSelectedClassifier(); CfsSubsetEval eval = new CfsSubsetEval(); GreedyStepwise search = new GreedyStepwise(); search.setSearchBackwards(true); J48 base = new J48(); classifier.setClassifier(base);//from w w w . jav a 2s . c om classifier.setEvaluator(eval); classifier.setSearch(search); Evaluation evaluation = new Evaluation(data); evaluation.crossValidateModel(classifier, data, 10, new Random(1)); System.out.println(evaluation.toSummaryString()); } protected static void useFilter(Instances data) throws Exception { weka.filters.supervised.attribute.AttributeSelection filter = new weka.filters.supervised.attribute.AttributeSelection(); CfsSubsetEval eval = new CfsSubsetEval(); GreedyStepwise search = new GreedyStepwise(); search.setSearchBackwards(true); filter.setEvaluator(eval); filter.setSearch(search); filter.setInputFormat(data); Instances newData = Filter.useFilter(data, filter); System.out.println(newData); } protected static void useLowLevel(Instances data) throws Exception { System.out.println("\n3. Low-level"); AttributeSelection attsel = new AttributeSelection(); CfsSubsetEval eval = new CfsSubsetEval(); GreedyStepwise search = new GreedyStepwise(); search.setSearchBackwards(true); attsel.setEvaluator(eval); attsel.setSearch(search); attsel.SelectAttributes(data); int[] indices = attsel.selectedAttributes(); System.out .println("selected attribute indices (starting with 0):\n" + Utils.arrayToString(indices)); } public static void main(String[] args) throws Exception { System.out.println("\n0. Loading data"); DataSource source = new DataSource(args[0]); Instances data = source.getDataSet(); if (data.classIndex() == -1) data.setClassIndex(data.numAttributes() - 1); useClassifier(data); useFilter(data); useLowLevel(data); } }