这次介绍如何利用weka里的类对数据集进行分类,要对数据集进行分类,第一步要指定数据集中哪一列做为类别,如果这一步忘记了(事实上经常会忘记)会出现“Class index is negative (not set)!”这个错误,设置某一列为类别用Instances类的成员方法setClassIndex,要设置最后一列为类别则可以用Instances类的numAttributes()成员方法得到属性的个数再减1。
然后选择分类器,比较常用的分类器有J48,NaiveBayes,SMO(LibSVM有Java版的,可以在weka中使用,但要设置路径),训练分类器使用J48的buildClassifier(注意J48还有别的分类器它们都继承自Classifier类,使用方法都差不多),分类数据用J48类中的classifyInstance方法,例中使用的数据集为contact-lenses.arff,分类结果为2.0,结果为2.0的原因是:首先用文本编辑器打开数据集,有一行为@attribute contact-lenses {soft, hard, none},而第一个样本为young, myope, no, reduced, none,最后一列为类别,也就是contact-lences为类别,第一个样本的类别为none,在属性说明中none为第二个所以为2.0(从0开始数)。
package com.cizito.weka.study; import weka.classifiers.bayes.NaiveBayes; import weka.classifiers.functions.SMO; import weka.classifiers.trees.J48; import weka.core.Instances; import weka.core.converters.ConverterUtils.DataSource; /** * @author zhangwei * */ public class ClassifierTest { private Instances m_instances = null; /** * @param args */ public static void main(String[] args) throws Exception{ ClassifierTest ctest = new ClassifierTest(); ctest.getFileInstances( "D:/ProgramFiles/Weka-3-6/data/contact-lenses.arff"); ctest.classify(); } public void getFileInstances( String fileName ) throws Exception { DataSource frData = new DataSource( fileName ); m_instances = frData.getDataSet(); m_instances.setClassIndex( m_instances.numAttributes()-1); } public void classify() throws Exception { //J48 classifier = new J48(); NaiveBayes classifier = new NaiveBayes(); //SMO classifier = new SMO(); classifier.buildClassifier( m_instances ); System.out.println( classifier.classifyInstance( m_instances.instance( 0 ) ) ); } }