我需要构建一个 Weka分类器,然后用它来预测 future 的实例。一个很好的入门资源是 here.不幸的是,我注意到 future 的实例不需要匹配源训练数据的格式。
如何根据训练数据和新实例之间的差异进行预测?
示例火车:
@relation train
@attribute A1 {e,f,g}
@attribute A2 numeric
@attribute A3 numeric
@attribute A4 {positive, negative}@data
e, -100, 100, positive
f, -10, 10, positive
g, -90, 90, negative
示例测试:
@relation test
@attribute B1 {b,a}
@attribute B2 numeric
@attribute B3 {good, bad}@data
b, 100, good
a, 10, bad
b, 90, good
如果保存上述训练和测试数据集,您可以使用以下代码来查看基于训练数据构建的模型能够从测试数据中对实例进行分类。
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 .
最佳答案
我知道这个问题很老,但我的回答可能会对其他人有所帮助。
Instances.equalHeaders(Instances)
方法正是您要找的。如果两个 Instances
兼容,则返回 true
,否则返回 false
。
关于java - 验证实例与 Weka 分类器的兼容性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34613691/