import java.io.*;
import weka.classifiers.*;
import weka.classifiers.meta.Vote;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.SelectedTag;
import weka.core.converters.ArffLoader;
public class test {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Instances tranIns=null; //训练数据
Instances testIns=null; //测试数据
Classifier cfs1=null; //分类器1
Classifier cfs2=null; //分类器2
Classifier cfs3=null; //分类器3
Classifier []cfsArray=new Classifier[3]; //分类器数组
try
{
File file=new File("C://Program Files//Weka-3-6//data//segment-challenge.arff"); //训练数据
ArffLoader loader=new ArffLoader();
loader.setFile(file);
tranIns=loader.getDataSet(); //读入数据
file=new File("C://Program Files//Weka-3-6//data//segment-test.arff"); //测试数据
loader.setFile(file);
testIns=loader.getDataSet();
testIns.setClassIndex(testIns.numAttributes()-1); //设置类别的位置
tranIns.setClassIndex(tranIns.numAttributes()-1);
cfs1=(Classifier)Class.forName("weka.classifiers.bayes.NaiveBayes").newInstance(); //算法
cfs2=(Classifier)Class.forName("weka.classifiers.trees.J48").newInstance();
cfs3=(Classifier)Class.forName("weka.classifiers.rules.ZeroR").newInstance();
cfsArray[0]=cfs1;
cfsArray[1]=cfs2;
cfsArray[2]=cfs3;
//分类器的决策方式
Vote ensemble=new Vote();
SelectedTag tag1=new SelectedTag(Vote.MAJORITY_VOTING_RULE,Vote.TAGS_RULES);//(投票)
ensemble.setCombinationRule(tag1);
ensemble.setClassifiers(cfsArray);
ensemble.setSeed(2); //设置随机种子
ensemble.buildClassifier(tranIns); //训练分类器
Instance testInst;
Evaluation testingEvaluation1=new Evaluation(testIns); //检测分类模型的类
Evaluation testingEvaluation2=new Evaluation(testIns);
Evaluation testingEvaluation3=new Evaluation(testIns);
Evaluation testingEvaluation4=new Evaluation(testIns);
int length=testIns.numInstances();
//单独学习
for(int i=0;i<length;i++)
{
testInst=testIns.instance(i);
testingEvaluation1.evaluateModelOnceAndRecordPrediction(cfs1, testInst);
}
System.out.println("分类正确率:"+(1- testingEvaluation1.errorRate()));
for(int i=0;i<length;i++)
{
testInst=testIns.instance(i);
testingEvaluation2.evaluateModelOnceAndRecordPrediction(cfs2, testInst);
}
System.out.println("分类正确率:"+(1- testingEvaluation2.errorRate()));
for(int i=0;i<length;i++)
{
testInst=testIns.instance(i);
testingEvaluation3.evaluateModelOnceAndRecordPrediction(cfs3, testInst);
}
System.out.println("分类正确率:"+(1- testingEvaluation3.errorRate()));
//集成学习
for(int i=0;i<length;i++)
{
testInst=testIns.instance(i);
testingEvaluation4.evaluateModelOnceAndRecordPrediction(ensemble, testInst);
}
System.out.println("分类正确率:"+(1- testingEvaluation4.errorRate()));
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
weka 集成学习