我正在使用 Weka 3.6.11,但遇到了一个错误,我无法弄清楚是什么导致了它。我遵循了 Weka 手册中的第 202-204 页,并像他们说的那样构建了我的数据。仍然当我尝试对数据进行分类时,我得到了一个错误。
weka.core.UnassignedDatasetException: Instance doesn't have access to a dataset!
Run Code Online (Sandbox Code Playgroud)
这是我到目前为止的代码:
public static void classifyTest()
{
try
{
Classifier classifier = (Classifier)weka.core.SerializationHelper.read("iris120.model");
System.Console.WriteLine("----------------------------");
weka.core.Attribute sepallength = new weka.core.Attribute("sepallength");
weka.core.Attribute sepalwidth = new weka.core.Attribute("sepalwidth");
weka.core.Attribute petallength = new weka.core.Attribute("petallength");
weka.core.Attribute petalwidth = new weka.core.Attribute("petalwidth");
FastVector labels = new FastVector();
labels.addElement("Iris-setosa");
labels.addElement("Iris-versicolor");
labels.addElement("Iris-virginica");
weka.core.Attribute cls = new weka.core.Attribute("class", labels);
FastVector attributes = new FastVector();
attributes.addElement(sepallength);
attributes.addElement(sepalwidth);
attributes.addElement(petallength);
attributes.addElement(petalwidth);
attributes.addElement(cls);
Instances dataset = new Instances("TestInstances", attributes, 0);
double[] values = new double[dataset.numAttributes()];
values[0] = 5.0;
values[1] = 3.5;
values[2] = 1.3;
values[3] = 0.3;
Instance inst = new Instance(1,values);
dataset.add(inst);
// Here I try to classify the data that I have constructed.
try
{
double predictedClass = classifier.classifyInstance(inst);
System.Console.WriteLine("Class1: (irisSetosa): " + predictedClass);
}
catch (java.lang.Exception ex)
{
ex.printStackTrace();
}
System.Console.ReadLine();
}
catch (java.lang.Exception ex)
{
ex.printStackTrace();
System.Console.ReadLine();
}
}
Run Code Online (Sandbox Code Playgroud)
从错误消息中,我认为我需要为我的数据集分配一些东西,但我不知道是什么或如何分配。有人可以指出我的错误吗?谢谢。
我找到了我自己问题的解决方案,因此我在这里提供信息,以便它可以帮助其他人。
我最初的问题是我收到了“UnsignedDataSetException”。为了解决这个问题,我向 setDataSet 添加了一个方法调用,如下所示:
....previous code omitted, can be seen in the question...
Instance inst = new Instance(1.0,values);
dataset.add(inst);
inst.setDataset(dataset);
....following code omitted, can be seen in the question...
Run Code Online (Sandbox Code Playgroud)
之后,我得到了另一个异常,称为 UnassignedClassException。这意味着您没有明确设置要用作预测结果的属性。通常它是最后一个属性,所以我们添加一个名为 setClassIndex 的方法,如下所示:
Instances dataset = new Instances("TestInstances", attributes, 0);
// Assign the prediction attribute to the dataset. This attribute will
// be used to make a prediction.
dataset.setClassIndex(dataset.numAttributes() - 1);
Run Code Online (Sandbox Code Playgroud)
现在它起作用了。它预测正确的虹膜(至少对于我尝试过的虹膜)。如果弹出其他内容,我将编辑此问题/答案。
干杯!