我正在使用 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 对测试实例进行分类的方式!