Java examples for Machine Learning AI:weka
weka SMOTE Stacking J48 BRF
import java.io.FileWriter; import java.util.ArrayList; import weka.classifiers.Classifier; import weka.classifiers.Evaluation; import weka.classifiers.bayes.NaiveBayes; import weka.classifiers.evaluation.Prediction; import weka.classifiers.meta.Bagging; import weka.classifiers.meta.Stacking; import weka.classifiers.trees.J48; import weka.classifiers.trees.RandomForest; import weka.core.Instances; import weka.core.converters.ConverterUtils.DataSource; import weka.filters.Filter; import weka.filters.supervised.instance.SMOTE; import au.com.bytecode.opencsv.CSVWriter; public class SMOTE_500_Stacking_NB_BJ48_BRF { public static void main(String[] args) throws Exception { /*from w w w.j a va 2 s . co m*/ Instances train = DataSource read("./train1.arff"); int cid1 = train.numAttributes() - 1; train.setClassIndex(cid1); Instances validation = DataSource read("./validation1.arff"); int cid2 = validation.numAttributes() - 1; validation.setClassIndex(cid2); Instances test = DataSource read("./test1.arff"); int cid3 = test.numAttributes() - 1; test.setClassIndex(cid3); NaiveBayes NB = new NaiveBayes(); J48 j48_tree = new J48(); RandomForest RF = new RandomForest(); Bagging b1 = new Bagging(); b1.setClassifier(j48_tree); Bagging b2 = new Bagging(); b2.setClassifier(RF); //SMOTE SMOTE sm = new SMOTE(); sm.setInputFormat(train); sm.setNearestNeighbors(5); sm.setPercentage(500); train = Filter.useFilter(train, sm); //Stacking NB BJ48 BRF Stacking tree = new Stacking(); Classifier[] classifiers = new Classifier[2]; classifiers[0] = b1; classifiers[1] = b2; tree.setClassifiers(classifiers); tree.setMetaClassifier(NB); tree.buildClassifier(train); Evaluation eval = new Evaluation(train); eval.evaluateModel(tree, validation); System.out.println(eval.toSummaryString("\nResults_RF\n\n", false)); System.out.println(eval.toClassDetailsString()); System.out.println(eval.toMatrixString()); ArrayList<Prediction> al = eval.predictions(); ArrayList<String[]> as = new ArrayList<String[]>(al.size()); for (int i = 0; i < al.size(); i++) { String[] s = new String[1]; s[0] = al.get(i).toString(); s[0] = s[0].substring(9, 11); as.add(s); } ArrayList<String[]> li = new ArrayList<String[]>(al.size()); li.addAll(as); String csv = "./output.csv"; CSVWriter writer = new CSVWriter(new FileWriter(csv)); writer.writeAll(li); writer.close(); } }