我使用Mallet训练主题模型,我想将其序列化以供以后使用。我在两个测试文档上运行它,然后对其进行反序列化并在相同的文档上运行加载的模型,结果完全不同。
我保存/加载文件的方式有什么问题(附带代码)?
谢谢!
List<Pipe> pipeList = initPipeList();
// Begin by importing documents from text to feature sequences
InstanceList instances = new InstanceList(new SerialPipes(pipeList));
for (String document : documents) {
Instance inst = new Instance(document, "","","");
instances.addThruPipe(inst);
}
ParallelTopicModel model = new ParallelTopicModel(numTopics, alpha_t * numTopics, beta_w);
model.addInstances(instances);
model.setNumThreads(numThreads);
model.setNumIterations(numIterations);
model.estimate();
printProbabilities(model, "doc 1"); // I replaced the contents of the docs due to copywrite issues
printProbabilities(model, "doc 2");
model.write(new File("model.bin"));
model = ParallelTopicModel.read("model.bin");
printProbabilities(model, "doc 1");
printProbabilities(model, "doc 2");
printProbabilities()
的定义:
public void printProbabilities(ParallelTopicModel model, String doc) {
List<Pipe> pipeList = initPipeList();
InstanceList instances = new InstanceList(new SerialPipes(pipeList));
instances.addThruPipe(new Instance(doc, "", "", ""));
double[] probabilities = model.getInferencer().getSampledDistribution(instances.get(0), 10, 1, 5);
for (int i = 0; i < probabilities.length; i++) {
double probability = probabilities[i];
if (probability > 0.01) {
System.out.println("Topic " + i + ", probability: " + probability);
}
}
}
答案 0 :(得分:2)
您必须使用相同的管道进行培训和分类。在训练期间,管道的数据字母表随每个训练实例更新。您不使用新的SerialPipe(pipeList)生成相同的管道,因为其数据字母表为空。保存/加载包含管道的管道或实例列表以及模型,并使用该管道添加测试实例。
答案 1 :(得分:0)
当你没有修复随机种子时,每次运行的Mallet都会为你提供一个不同的主题模型(主题数量置换,一些主题略有不同,其他主题非常不同)。
修复随机种子以获取可复制的主题。