weka之调用特征选择

参考文献
http://download.csdn.net/detail/kaikai_sk/9854774

package FilterTest;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Random;

import weka.attributeSelection.CfsSubsetEval;
import weka.attributeSelection.GreedyStepwise;
import weka.classifiers.Evaluation;
import weka.classifiers.meta.AttributeSelectedClassifier;
import weka.classifiers.trees.J48;
import weka.core.Instances;
import weka.filters.Filter;
import weka.filters.supervised.attribute.AttributeSelection;

public class FilterTest 
{
    Instances m_instances=null;

    public void getFileInstances(String fileName) throws Exception
    {
        FileReader frData=new FileReader(fileName);
        m_instances=new Instances(frData);
        m_instances.setClassIndex(m_instances.numAttributes()-1);
    }

    public void selectAttUseFilter() throws Exception
    {
        weka.filters.supervised.attribute.AttributeSelection filter=new 
                AttributeSelection();
        CfsSubsetEval eval=new CfsSubsetEval();
        GreedyStepwise search=new GreedyStepwise();
        filter.setEvaluator(eval);
        filter.setSearch(search);
        filter.setInputFormat(m_instances);

        System.out.println("number of instances attribute ="+
        m_instances.numAttributes());
        Instances selectedInstances=Filter.useFilter(m_instances, filter);
        System.out.println("number of selected instances attribute ="+
        selectedInstances.numAttributes());
    }

    public void selectAttUseMc() throws Exception
    {
        AttributeSelectedClassifier classifier=new AttributeSelectedClassifier();
        CfsSubsetEval eval=new CfsSubsetEval();
        GreedyStepwise search=new GreedyStepwise();
        J48 base=new J48();
        classifier.setClassifier(base);
        classifier.setEvaluator(eval);
        classifier.setSearch(search);

        //进行十折交叉验证
        Evaluation evaluation=new Evaluation(m_instances);
        evaluation.crossValidateModel(classifier, m_instances, 10, new Random(1));
        System.out.println(evaluation.toSummaryString());
    }

    public static void main(String[] args) throws Exception
    {
        FilterTest filterTest=new FilterTest();
        filterTest.getFileInstances("E:\\Program Files\\Weka-3-8\\data\\weather.nominal.arff");
        filterTest.selectAttUseFilter();
        filterTest.selectAttUseMc();
    }
}

你可能感兴趣的:(机器学习)