我正在使用Weka 3.6.13(发布时为最新),但似乎无法让AdaBoostM1选择分类器。我想包括AdaBoostM1以及基本分类器的选项。但是函数setClassifier()似乎并不存在于JAR中,而是存在于Docs中。
import java.io.*;
import weka.classifiers.Classifier;
import weka.classifiers.Evaluation;
import weka.classifiers.evaluation.NominalPrediction;
import weka.classifiers.meta.AdaBoostM1;
import weka.classifiers.trees.RandomForest;
import weka.core.FastVector;
import weka.core.Instances;
public class ULCWekaTest
{
public static Evaluation classify(Classifier model,
Instances trainingSet, Instances testingSet)
throws Exception
{
Evaluation evaluation = new Evaluation(trainingSet);
model.buildClassifier(trainingSet);
evaluation.evaluateModel(model, testingSet);
return evaluation;
}
public static double calculateAccuracy(FastVector predictions)
{
double correct = 0;
for(int i = 0; i < predictions.size(); i++)
{
NominalPrediction np = (NominalPrediction) predictions.elementAt(i);
if(np.predicted() == np.actual())
correct++;
}
return 100 * correct / predictions.size();
}
public static void main(String[] args) throws Exception
{
String basepath =
"/Users/Ebe/Pantheon/Ares/PhD/Course Work/MLT/MLT-Lab/Mini Project/Implementation/";
Instances trainData;
try(BufferedReader reader =
new BufferedReader(
new FileReader(basepath + "train80.arff")))
{
trainData = new Instances(reader);
reader.close();
}
trainData.setClassIndex(0);
Instances testData;
try(BufferedReader reader =
new BufferedReader(
new FileReader(basepath + "test80.arff")))
{
testData = new Instances(reader);
reader.close();
}
testData.setClassIndex(0);
Classifier forest, adaboost;
String[] options = new String[2];
for(int i = 100; i < 500; i+=2)
{
for(int s = 6; s <= 6; s++)
{
adaboost = new AdaBoostM1();
forest = new RandomForest();
//for(String str : forest.getOptions())
// System.out.println(str);
options[0] = "-I";
options[1] = ""+i;
forest.setOptions(options);
options[0] = "-S";
options[1] = "" + s;
forest.setOptions(options);
adaboost.setClassifier(forest); // <-- COMPILER ERROR AT THIS POINT
// Collect every group of predictions for current model in a FastVector
FastVector predictions = new FastVector();
// For each training-testing split pair, train and test the classifier
Evaluation validation =
classify(adaboost, trainData, testData);
predictions.appendElements(validation.predictions());
// Calculate overall accuracy of current classifier on all splits
double accuracy = calculateAccuracy(predictions);
// Print current classifier's name and accuracy in a complicated,
// but nice-looking way.
System.out.println("-I " + i + " -S " + s + ": " + String.format(
"%.2f%%", accuracy));
}
}
}
}
难道我做错了什么?如何解决这个问题?谁能解释或至少提供一个Java示例AdaBoostM1-Weka代码的链接?
最佳答案
正在使用Classifier
类。这是AdaBoostM1
和RandomForest
分类器的基类。因此,您将无法访问selectClassifier()
方法,因为它是从Classifier
派生的类访问的。
改变这条线
Classifier forest, adaboost;
至
Classifier forest;
AdaBoostM1 adaboost;
解决了问题。