我用来训练模型并使用模型再次分类。
我正确地得到了第一部分的统计数据,但没有得到第二部分的统计数据。 它再次评估时会给出nullPointerException。我尝试过所有类型的操作,比如在代码等中创建的一个实例上测试它。
java.lang.NullPointerException
at weka.classifiers.trees.m5.M5Base.classifyInstance(M5Base.java:514)
at wekaTest.<init>(wekaTest.java:44)
at wekaTest.main(wekaTest.java:71)
我写的代码片段是:
wekaTest()
{
try
{
FileReader reader = new FileReader("3.arff");
Instances instances = new Instances(reader);
// Make the last attribute be the class
int numAttr = instances.numAttributes();
instances.setClassIndex( numAttr - 1);
M5P tree = new M5P();
Evaluation eval = new Evaluation(instances);
eval.crossValidateModel(tree, instances, 10, new Random(1));
System.out.println(eval.toSummaryString("\nResults\n======\n", false));
weka.core.SerializationHelper.write("/path/tree.model", tree);
reader.close();
FileReader reader2 = new FileReader("3.arff");
Instances instances2 = new Instances(reader2);
instances2.setClassIndex(instances2.numAttributes() - 1);
reader2.close();
Instances labeled = new Instances(instances2);
Classifier cls = (Classifier) weka.core.SerializationHelper.read("/path/tree.model");
//instances2.deleteAttributeAt(numAttr-1);
for(int j=0; j<instances2.numInstances() ;j++)
{
//instance temp = new instance(instances2.instance(j));
//instances2.instance(j).setValue(numAttr-1,-1);
System.out.println("The instance: " + instances2.instance(j));
double clsLabel = tree.classifyInstance(instances2.instance(j));
labeled.instance(j).setClassValue(clsLabel);
}
}
catch(Exception ex) { ex.printStackTrace(); }
}
答案 0 :(得分:3)
可能是您正在编写的树尚未初始化。
答案 1 :(得分:1)
谢谢Aditya。其实你是对的!当我在10次交叉验证后编写它时,该变量尚未初始化。
摘录如下:
try
{
FileReader reader2 = new FileReader("3.arff");
Instances instances2 = new Instances(reader2);
instances2.setClassIndex(instances2.numAttributes() - 1);
reader2.close();
int numAttr = instances2.numAttributes();
Instances labeled = new Instances(instances2);
Classifier cls = (Classifier) weka.core.SerializationHelper.read("/home/sumit/Desktop/weka test/tree.model");
cls.setDebug(true);
Instance inst = new Instance(4);
inst.setValue(0, instances2.instance(0).value(0));
inst.setValue(1, instances2.instance(0).value(1));
inst.setValue(2, instances2.instance(0).value(2));
inst.setValue(3, -1);
double clsLabelTest = cls.classifyInstance(inst);
System.out.println(clsLabelTest);
//instances2.deleteAttributeAt(numAttr-1);
for(int j=0; j<instances2.numInstances() ;j++)
{
//instance temp = new instance(instances2.instance(j));
instances2.instance(j).setValue(numAttr-1,-1);
//System.out.println("The instance: " + instances2.instance(j));
double clsLabel = cls.classifyInstance(instances2.instance(j));
labeled.instance(j).setClassValue(clsLabel);
}
BufferedWriter writer = new BufferedWriter(new FileWriter("/home/sumit/Desktop/weka test/labeled.arff"));
writer.write(labeled.toString());
writer.newLine();
writer.flush();
writer.close();
// Test the model
//Evaluation eTest = new Evaluation(instances2);
//eTest.evaluateModel(cls, instances2);
}