【问题标题】:Verify compatibility of instance with Weka classifier验证实例与 Weka 分类器的兼容性
【发布时间】:2016-04-09 09:30:32
【问题描述】:

我需要构建一个Weka 分类器,然后用它来预测未来的实例。一个很好的入门来源是here. 不幸的是,我注意到未来的实例不需要匹配源训练数据的格式

如何根据训练数据和新实例之间的差异做出预测?

火车示例:

@关系火车

@attribute A1 {e,f,g}
@attribute A2 数字
@attribute A3 数字
@attribute A4 {正面,负面}

@数据
e, -100, 100, 正
f, -10, 10, 正
g, -90, 90, 负数

示例测试:

@关系测试

@attribute B1 {b,a}
@属性 B2 数字
@attribute B3 {好,坏}

@数据
b,100,好
一,10,坏
b、90、好

如果您保存上述训练和测试数据集,您可以使用以下代码查看基于训练数据构建的模型能够从测试数据中对实例进行分类。

import java.io.BufferedReader;
import java.io.FileReader;
import weka.classifiers.Classifier;
import weka.classifiers.bayes.NaiveBayes;
import weka.core.Instances;

public class Main {
    public static void main(String[] args) throws Exception {

        //
        // Load train data
        // 
        String readTrain = "someWhere/train.arff";
        BufferedReader readerTrain = new BufferedReader(new FileReader(readTrain));
        Instances train = new Instances(readerTrain);
        readerTrain.close();
        train.setClassIndex(train.numAttributes() - 1);         

        //
        // Load test data
        // 
        String readTest = "someWhere/test.arff";
        BufferedReader readerTest = new BufferedReader(new FileReader(readTest));
        Instances test = new Instances(readerTest);
        readerTest.close();
        test.setClassIndex(test.numAttributes() - 1);  

        // Create a naïve bayes classifier
        Classifier cModel = (Classifier)new NaiveBayes();
        cModel.buildClassifier(train);

        // Predict distribution of instance
        double[] fDistribution = cModel.distributionForInstance(test.instance(2));
        System.out.println("Prediction class 1: " + fDistribution[0]);
        System.out.println("Prediction class 2: " + fDistribution[1]);
    }
}

任何关于如何使用不同数据源进行预测的解释,或强制新实例与分类器的原始训练数据格式相匹配的想法,我们都非常感谢。但是我不想依赖Evaluation class

【问题讨论】:

  • 非常有趣的问题。只是补充一点,如果您在测试集上构建模型并在训练集上对其进行测试,则它不起作用。此外,如果您在代码中使用 SMO 而不是 NaiveBayes,它会为您提供预期的错误消息:属性不匹配!

标签: java weka


【解决方案1】:

如果可以的话,您可以测试一个新实例与用于构建分类器的数据集 [trainset.checkInstance(yourInstance)]。这保证了兼容性。如果训练集太大,您可以通过过滤对其进行子样本。这样,您可以测试是否有任何新实例满足您的分类器的要求。

【讨论】:

    【解决方案2】:

    我知道这个问题很老,但我的回答可能对其他人有所帮助。

    Instances.equalHeaders(Instances) 方法就是你要找的。如果Instances 兼容,则返回true,否则返回false

    【讨论】:

      猜你喜欢
      • 2015-12-27
      • 2021-04-14
      • 2012-03-25
      • 2013-05-13
      • 2012-06-30
      • 2015-02-01
      • 2011-09-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多