首页 > 解决方案 > 删除 Weka ML 模型的测试 ARFF 文件中的最后一个类属性在预测模型中不起作用

问题描述

基本上,我正在用 Java (Weka) 构建一个机器学习模型来检测字符串中的一些模式。我有 2 个类属性,我试图让我的模型根据这些模式进行预测。当我将属性值保留在 ARFF 文件中时,我的代码可以工作,但是当我将其取出并用测试文件中的问号替换它时,它就不行了。当我这样做时,它会在输出中为我提供所有相同的值 (cfb)。我知道模型不是硬编码的,但出于测试目的,我想删除这些属性值。我已经建立了分类器并评估了模型。

 /**
 * Make predictions based on that model. Improve the model
 * 
 * @throws Exception
 */
public void modelPredictions(Instances trainedDataSet, Instances testedDataSet, Classifier classifierType) throws Exception {
    // Get the number of classes
    int numClasses = trainedDataSet.numClasses();
    // print out class values in the training dataset
    for (int i = 0; i < numClasses; i++) {
        // get class string value using the class index
        String classValue = trainedDataSet.classAttribute().value(i);
        System.out.println("Class Value " + i + " is " + classValue);
    }
    // set class index to the last attribute
    // loop through the new dataset and make predictions
    System.out.println("===================");
    System.out.println("Actual Class, NB Predicted");
    for (int i = 0; i < testedDataSet.numInstances(); i++) {
        // get class double value for current instance
        double actualClass = testedDataSet.instance(i).classValue();
        // get class string value using the class index using the class's int value
        String actual = testedDataSet.classAttribute().value((int) actualClass);
        // get Instance object of current instance
        Instance newInst = testedDataSet.instance(i);
        // call classifyInstance, which returns a double value for the class
        double predNB = classifierType.classifyInstance(newInst);
        // use this value to get string value of the predicted class
        String predString = testedDataSet.classAttribute().value((int) predNB);
        System.out.println(actual + ", " + predString);
    }
}

测试 ARFF 文件的图像(抱歉,在粘贴文件的文件内容时出错。

标签: javamachine-learningweka

解决方案


如果您用问号替换测试集中的实际类,这些会被解释为缺失值。Weka 中的缺失值由 表示Double.NaN。将缺失值(即 Double.NaN)转换为 anint将导致0,这是您班级的第一个标称值。您的实际班级将永远是一流的标签。

以下代码:

double missing = Utils.missingValue();
System.out.println("missing value as double: " + missing);
System.out.println("missing value as int: " + ((int) missing));

输出这个:

missing value as double: NaN
missing value as int: 0

推荐阅读