使用Weka编写分类器

时间:2015-02-26 16:34:57

标签: tree classification weka

我的英语很糟糕,但我会尽力说清楚。 我想用Weka编写一个分类器(例如J48)。 在我的例子中,一个实例由六个数字组成,所有数字都在0到10之间,除了一个介于0和-10之间的数字。

例子: 1,-3,6,3,6,7或 1,-4,5,3,7,6或 2,-4,5,3,8,6

在ARFF:

@ATTRIBUTE attribute1 {0,1,2,3,4,5,6,7,8,9,10}

@ATTRIBUTE attribute2 {0,-1,-2,-3,-4,-5,-6,-7,-8,-9,-10}

@ATTRIBUTE attribute3 {0,1,2,3,4,5,6,7,8,9,10}

...

这个实例(例子)都是“好的”。我想知道是否可以创建一个分类器。我会给它一个新的实例,如果这个实例好或不好,它可以回答(百分比)。 我问,因为我不知道如何选择类索引或结果变量......

1 个答案:

答案 0 :(得分:1)

我正在使用Weka概述最基本的怎么做分类

培训档案 你需要一个培训文件。 Weka将许多不同的格式视为训练文件(以及测试文件)。其中包括ARFF(属性 - 关系文件格式)和CSV(逗号分隔值)格式。假设我们有一个ARFF格式的培训文件。该文件的一部分如下所示:

@relation pima_diabetes
@attribute 'preg' real
@attribute 'plas' real
@attribute 'pres' real
@attribute 'skin' real
@attribute 'insu' real
@attribute 'mass' real
@attribute 'pedi' real
@attribute 'age' real
@attribute 'class' { tested_negative, tested_positive}
@data
6,148,72,35,0,33.6,0.627,50,tested_positive
1,85,66,29,0,26.6,0.351,31,tested_negative

请注意,要培养良好的学习者,您需要拥有大量的培训数据。同样,您的所有课程都应该在您的训练数据中得到充分体现,以便您从中开发的分类器具有区分能力。

测试文件 如上所述,测试文件也可以有许多不同的形式。比如说,我们的测试文件是ARFF格式,测试文件的一部分如下:

@attribute 'preg' real
@attribute 'plas' real
@attribute 'pres' real
@attribute 'skin' real
@attribute 'insu' real
@attribute 'mass' real
@attribute 'pedi' real
@attribute 'age' real
@attribute 'class' { tested_negative, tested_positive}
@data
5,116,74,0,0,25.6,0.201,30,?
3,78,50,32,88,31,0.248,26,?

请注意,测试数据的类标签是'?'标签,因为标签是未知的,由您根据培训数据开发的分类器确定。

代码 使用Java API,一个简单的方法来设置我们的分类器并在训练数据上构建它并最后应用它来分类未知的,未标记的测试实例可以如下:

/**
     * Method to build the naive bayes classifier and classify test documents
     */
    public void classify(){
        //setting the classifier--->
        fc = new FilteredClassifier();
        nb = new NaiveBayes();      
        fc.setFilter(filter);
        fc.setClassifier(nb);
        //<---setting of the classifier ends
        //building the classifier--->

        try {
            fc.buildClassifier(data);
        } catch (Exception e) {
            System.out.println("Error from Classification.classify(). Cannot build classifier");
        }
        //<---building of the classifier ends
        //Classification--->
        clsLabel = new double[testData.numInstances()]; //holds class label of the test documents
        //for each test document--->
        for (int i = 0; i < testData.numInstances(); i ++){
            try {
                clsLabel[i] = fc.classifyInstance(testData.instance(i));
            } catch (Exception e) {
                System.out.println("Error from Classification.classify(). Cannot classify instance");
            }
            testData.instance(i).setClassValue(clsLabel[i]);
        }//end for
        //<---classification ends
    }//end method

这就是你使用Weka对测试实例进行分类的方法!