Weka可以作为一个包导入到eclipse工程中,具体看截图
示例代码如下:
package com.mycompany.project;
import java.io.File;
import java.util.Random;
import weka.classifiers.Evaluation;
import weka.classifiers.trees.J48;
import weka.core.Instances;
import weka.core.converters.ArffLoader;
public class J48DecisionTree {
public static void main(String[] args) {
Instances instances= null;
try {
File file = new File("C:\\Program Files\\Weka-3-6\\data\\weather.nominal.arff");
//ARFF数据加载器
ArffLoader loader = new ArffLoader();
//加载数据
loader.setFile(file);
//获得数据集
instances = loader.getDataSet();
// 在使用样本之前一定要首先设置instances的classIndex,否则在使用instances对象是会抛出异常
instances.setClassIndex(instances.numAttributes() - 1);
//评估器,评估模型
Evaluation eval = new Evaluation(instances);
//J48决策树分类器
J48 tree = new J48();
//进行十折交叉验证
eval.crossValidateModel(tree, instances, 10, new Random(1));
//打印验证结果
System.out.println(eval.toSummaryString("\nResults\n\n", false));
//打印信息
System.out.println(eval.toMatrixString());
} catch (Exception e) {
// TODO: handle exception
}
}
}
Results
Correctly Classified Instances 7 50 %
Incorrectly Classified Instances 7 50 %
Kappa statistic -0.0426
Mean absolute error 0.4167
Root mean squared error 0.5984
Relative absolute error 87.5 %
Root relative squared error 121.2987 %
Total Number of Instances 14
=== Confusion Matrix ===
a b <-- classified as
5 4 | a = yes
3 2 | b = no