上学期我有一个项目,当给定一组汽车数据时,我必须建立一个模型并使用该模型从用户输入的数据中进行预测(它涉及 GUI 等)。教授介绍了 Weka,但只是以它的 GUI 形式。我正在重新创建项目,但这次是使用 Weka 库。这是有问题的课程:
public class TreeModel {
private J48 model = new J48();
private String[] options = new String[1];
private DataSource source;
private Instances data;
private Evaluation eval;
// Constructor
public TreeModel(String file) throws Exception {
source = new DataSource(file);
// By default, the options are set to produce unpruned tree '-U'
options[0] = "-U";
data = source.getDataSet();
model.setOptions(options);
}
// Overloaded constructor allowing you to choose options for the model
public TreeModel(String file, String[] options) throws Exception {
DataSource source = new DataSource(file);
data = source.getDataSet();
model.setOptions(options);
}
// Builds the decision tree
public void buildDecisionTree() throws Exception {
data.setClassIndex(data.numAttributes() - 1);
model.buildClassifier(data);
}
/*
* Uses cross validation technique to calculate the accuracy.
* Gives a more respected accuracy that is more likely to hold
* with instances not in the dataset.
*/
public void crossValidatedEvaluation(int folds) throws Exception {
eval = new Evaluation(data);
eval.crossValidateModel(model, data, folds, new Random());
System.out.println("The model predicted "+eval.pctCorrect()+" percent of the data correctly.");
}
/*
* Evaluates the accuracy of a decision tree when using all available data
* This should be looked at with skepticism (less interpretable)
*/
public void evaluateModel() throws Exception {
eval = new Evaluation(data);
eval.evaluateModel(model, data);
System.out.println("The model predicted "+eval.pctCorrect()+" percent of the data correctly.");
}
/*
* Returns a prediction for a particular instance. Will take in an instance
* as a parameter.
*/
public String getPrediction() throws Exception {
DataSource predFile = new DataSource("./predict.arff");
Instances pred = predFile.getDataSet();
Instance predic = pred.get(0);
pred.setClassIndex(pred.numAttributes() - 1);
double classify = model.classifyInstance(predic);
pred.instance(0).setClassValue(classify);
return pred.instance(0).stringValue(6);
}
// Returns source code version of the model (warning: messy code)
public String getModelSourceCode() throws Exception {
return model.toSource("DecisionTree");
}
}
在我的 getPrediction() 方法中,我有一个简单的示例,用于获取 ARFF 文件中实例的预测。问题是我无法弄清楚如何初始化单个 Instance 对象,然后将我想要进行预测的数据放入“in”该实例中。我查看了 Instance 类的文档,但乍一看什么也没看到。有没有办法手动将数据放入实例中,或者我需要将我的预测数据转换为 ARFF 文件?