我在java中尝试weka库。我连接sql server并拉取我的数据。并分裂测试和训练。我为测试和训练设置了类索引。这是我的代码部分;
Instances data = new Instances(datafile);
data.setClassIndex(data.numAttributes() - 1);
int trainSize = (int) Math.round(data.numInstances() * 0.8);
int testSize = data.numInstances() - trainSize;
Instances train = new Instances(data, 0, trainSize);
Instances test = new Instances(data, trainSize, testSize);
train.setClassIndex(train.numAttributes() - 1);
test.setClassIndex(test.numAttributes() - 1);
Classifier[] models =
{
new J48(),
new PART(),
new DecisionTable(),
new DecisionStump(),
new NaiveBayes(),
new IBk()
};
// Run for each model
for (int j = 0; j < models.length; j++)
{
FastVector predictions = new FastVector();
Evaluation validation = classify(models[j], train, test);
predictions.appendElements(validation.predictions());
}
}
我在这一行得到了错误;
Evaluation validation = classify(models[j], train, test);,
我在互联网上搜索此错误,用户说写这样的代码;
train.setClassIndex(train.numAttributes() - 1);
test.setClassIndex(test.numAttributes() - 1);
但我又得到了同样的错误。像这样的完整错误;
Exception in thread "main" weka.core.UnassignedClassException: Class index is negative (not set)!
at weka.core.Instances.numClasses(Instances.java:915)
at weka.classifiers.evaluation.Evaluation.<init>(Evaluation.java:461)
at weka.classifiers.evaluation.Evaluation.<init>(Evaluation.java:441)
at weka.classifiers.Evaluation.<init>(Evaluation.java:211)
at weka1.Weka1.classify(Weka1.java:84)
at weka1.Weka1.main(Weka1.java:193)