【发布时间】: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,它会为您提供预期的错误消息:属性不匹配!