我能够使用内置的lee_background语料库来构建模型。但是,当我尝试使用most_similar方法进行比较时,出现错误。
lee_train_file = '/opt/conda/lib/python3.6/site-packages/gensim/test/test_data/lee_background.cor'
train_corpus=list()
with open(lee_train_file) as f:
for i, line in enumerate(f):
train_corpus.append(gensim.models.doc2vec.TaggedDocument(gensim.utils.simple_preprocess(line), [i]))
model = gensim.models.doc2vec.Doc2Vec(vector_size=48, min_count=2, epochs=40)
model.build_vocab(train_corpus)
model.wv.vocab['penalty'].count
model.train(train_corpus, total_examples=model.corpus_count, epochs=model.epochs)
line="""
dummy text here...
"""
inferred_vector=model.infer_vector(gensim.utils.simple_preprocess(line) )
model.docvecs.most_similar(inferred_vector, topn=3)
我尝试使用list(inferred_vector)进行此操作,但仍然出现错误。
TypeError:“ numpy.float32”对象不可迭代
我正在尝试将虚拟文本与语料库进行比较,以查找条目是否已存在于数据文件中。
更新: 而不是list(inferred_vector),我需要使用[inferred_vector]。这解决了我的问题。但是每次我运行此代码时,都会得到不同的相似文档。这怎么可能?
line="""
The national executive of the strife-torn Democrats last night appointed little-known West Australian senator Brian Greig
as interim leader--a shock move likely to provoke further conflict between the party's senators and its organisation.
In a move to reassert control over the party's seven senators, the national executive last night rejected Aden Ridgeway's
bid to become interim leader, in favour of Senator John, a supporter of deposed leader Natasha Stott Despoja and an outspoken
gay rights activist.
"""
inferred_vector=model.infer_vector(gensim.utils.simple_preprocess(line))
model.docvecs.most_similar([inferred_vector], topn=5)
有时候我会得到这个列表,即使我的模型没有变化,每次运行代码时,列表也会不断变化。
[(151, 0.5980586409568787),
(74, 0.5736572742462158),
(106, 0.5714541077613831),
(249, 0.5695925951004028),
(209, 0.5642371773719788)]
[(249, 0.5727256536483765),
(151, 0.5725511312484741),
(74, 0.5711895823478699),
(106, 0.5583171248435974),
(292, 0.5491517782211304)]
事实上,训练语料库的第一行与该行相似,因为只有1个单词被更改,因此它的相似度为99%。令人惊讶的是,document_id 1在前5名列表中没有。
答案 0 :(得分:0)
虚拟线应从lee_background.cor中选择,而不是从lee.cor中选择 模型文本将与训练语料而不是测试语料匹配。