在我的项目中,我使用Python库gensim https://radimrehurek.com/gensim/models/wrappers/ldamallet.html用于主题建模/文本提取。
我尝试加载经过训练的 LdaMallet 模型来对新的未见过的文本进行分类。
第一部分是加载模型。
import os
dirname = os.path.dirname(__file__)
filename = os.path.join(dirname, 'mallet-2.0.8/bin/mallet')
# Download File: http://mallet.cs.umass.edu/dist/mallet-2.0.8.zip
os.environ['MALLET_HOME'] = # path to mallet
ldaMallet = gensim.models.wrappers.LdaMallet.load('lda_malletoutputCommentsAndMethods.model)
ldaModel = gensim.models.wrappers.ldamallet.malletmodel2ldamodel(ldaMallet)
我不确定将 ldaMallet 转换为 LdaModel 的最后一行。这是获得一些结果的唯一方法。
然后第二部分是准备新数据并对其进行分类。
from gensim.test.utils import common_dictionary
other_texts = [['new', 'document', 'to', 'classify', 'as', 'array']]
other_corpus = [common_dictionary.doc2bow(text) for text in other_texts]
vector = ldaModel[other_corpus[0]]
# sorts the result by probability and not by topic ID
print(sorted(vector, key=lambda x: x[1], reverse=True))
然后结果看起来像这样:
[(16, 0.143), (17, 0.08), (9, 0.0653),...]
无论我在其中使用哪个文本other_texts
数组,这个结果没有改变,但它应该改变。