我想对新实例进行分类,但我不想加载数据集来对其进行分类,我该怎么做?

I would like to classify new instance but I don't want to load the dataset to classify it how could I do that?

我用来构建classifier的数据集只有两个属性,第一个是字符串注释,第二个是标称的class,但是数据集太大我不知道我想将它加载到服务器中,所以我想使用该模型 class 验证新实例而不加载数据集。 因此,例如,假设我根据一些用户评论创建了一个新实例

String usercomment;
Instance instance = new Instance(2);
instance.setValue(0, usercomment);
instance.setMissing(1);

我知道我必须为实例设置数据集,但我不想加载,所以如何为实例创建具有相似属性的虚拟数据集?还 我正在使用旧的 weka 库,我认为我需要使用 fastvectors。

您不需要加载数据集来对新实例进行分类。您可以在数据集上训练您的模型,然后保存该模型。稍后,您加载此模型以对新实例进行分类。参见 Saving and loading models

加载模型后,您可以对实例进行分类,请参阅Classifying instances in Use Weka in your Java code

我在下面的 git 存储库 WekaExamples 中写了一个示例代码。我也在此处复制粘贴代码,但在该存储库中工作示例。 你可以在命令行中运行它。

gradlew loadArffAndTrainModelExample1 loadModelAndTestExampleInstance1

加载Arff

String datasetName = "weather.nominal";
Instances data = DataSetHelper.getInstanceFromFile("data/" + datasetName + ".arff");

// weka.classifiers.trees.J48 -C 0.25 -M 2
String classifierFullName = "weka.classifiers.trees.J48"
String optionString = " -C 0.25 -M 2"

AbstractClassifier classifier = (AbstractClassifier) Class.forName(classifierFullName).newInstance();

classifier.setOptions(Utils.splitOptions(optionString));
classifier.buildClassifier(data); // build classifier


String modelFullFileName = Finals.MODELS_SAVE_FOLDER + classifier.getClass().getName()  + ".model";
SerializationHelper.write(modelFullFileName, classifier);

loadModelAndTestExampleInstance1

String datasetName = "weather.nominal.only.header";
Instances data = DataSetHelper.getInstanceFromFile("data/" + datasetName + ".arff");



Instance inst = new DenseInstance(data.numAttributes()); 

inst.setDataset(data);

inst.setValue(0, 1); 
inst.setValue(1, 2); 
inst.setValue(2, 0); 
inst.setValue(3, 1); 

println(inst)



Classifier cls = (Classifier) SerializationHelper.read("models/weka.classifiers.trees.J48.model");
double prediction = cls.classifyInstance(inst);

println("prediction as double: " + prediction);
println("prediction as name: " + data.classAttribute().value((int) prediction));

代码输出如下

:compileJava UP-TO-DATE
:compileGroovy UP-TO-DATE
:processResources UP-TO-DATE
:classes UP-TO-DATE
:loadModelAndTestExampleInstance1
overcast,cool,high,FALSE,?
prediction as double: 0.0
prediction as name: yes

BUILD SUCCESSFUL