我已经有了一个使用 SimpleTagger 训练过的 CRF 训练模型。
SimpleTagger.main(new String[] {
"--train", "true",
"--model-file", "/Desktop/crfmodel",
"--threads", "8",
"--training-proportion", "0.8",
"--weights", "dense",
"--test", "lab",
// "--orders", "2",
"/Desktop/annotations.txt"
});
我计划加载此模型并将其用于标记。我正在使用这段代码。
public static void main(String[] args) throws Exception {
//DOCS http://mallet.cs.umass.edu/classifier-devel.php
Instance instance = getMyInstance();
Classifier classifier = loadClassifier(Paths.get("/Desktop/crfmodel").toFile());
Labeling labeling = classifier.classify(instance).getLabeling();
Label l = labeling.getBestLabel();
System.out.print(instance);
System.out.println(l);
}
private static Classifier loadClassifier(File serializedFile)
throws FileNotFoundException, IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream (new FileInputStream(serializedFile));
Classifier crf = (Classifier) ois.readObject();
ois.close();
return crf;
}
当我尝试执行上述操作时,出现以下错误
Exception in thread "main" java.lang.ClassCastException: cc.mallet.fst.CRF cannot be cast to cc.mallet.classify.Classifier
at TagClassifier.loadClassifier(TagClassifier.java:77)
at TagClassifier.main(TagClassifier.java:64)
错误发生在行中
Classifier crf = (Classifier) ois.readObject();
我可以知道为什么会发生这种情况吗?另外,如果有正确的记录方法使用经过训练的模型来标记输入,您可以分享任何链接/文档吗?预先非常感谢您!!!
最佳答案
我想我通过查看 SimpleTagger 代码找到了答案。
crfModel = loadClassifier(Paths.get("/Desktop/crfmodel").toFile());
pipe = crfModel.getInputPipe();
pipe.setTargetProcessing(false);
String formatted = getFormattedQuery(q);
Instance instance = pipe.pipe(new Instance(formatted, null, null, null));
Sequence sequence = (Sequence) instance.getData();
Sequence[] tags = tag(sequence, 3);
private static Sequence[] tag(Sequence input, int bestK) {
Sequence[] answers;
if (bestK == 1) {
answers = new Sequence[1];
answers[0] = crfModel.transduce(input);
} else {
MaxLatticeDefault lattice = new MaxLatticeDefault(crfModel, input, null);
answers = lattice.bestOutputSequences(bestK).toArray(new Sequence[0]);
}
return answers;
}
关于nlp - 使用 Mallet 加载模型并对输入进行分类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61071307/