【问题标题】:Determine most similar phrase with word2vec用 word2vec 确定最相似的短语
【发布时间】:2019-05-02 09:15:24
【问题描述】:

我创建了一个 Python 脚本,用于使用 doc2vec 训练和推断测试文档向量。

我的问题是,当我尝试确定最相似的短语(例如“世界”)时,它只会在最相似的单词列表中显示我。它没有显示最相似短语的列表。

我的代码中是否缺少某些内容?

#python example to infer document vectors from trained doc2vec model
import gensim.models as g
import codecs

#parameters
model="toy_data/model.bin"
test_docs="toy_data/test_docs.txt"
output_file="toy_data/test_vectors.txt"

#inference hyper-parameters
start_alpha=0.01
infer_epoch=1000

#load model
m = g.Doc2Vec.load(model)
test_docs = [ x.strip().split() for x in codecs.open(test_docs, "r", "utf-8").readlines() ]

#infer test vectors
output = open(output_file, "w")
for d in test_docs:
    output.write( " ".join([str(x) for x in m.infer_vector(d, alpha=start_alpha, steps=infer_epoch)]) + "\n" )
output.flush()
output.close()


m.most_similar('the word'.split())

我得到了这份清单:

[('refutations', 0.9990279078483582),
 ('volume', 0.9989271759986877),
 ('italic', 0.9988381266593933),
 ('syllogisms', 0.998751699924469),
 ('power', 0.9987285137176514),
 ('alibamu', 0.9985184669494629),
 ("''", 0.99847412109375),
 ('roman', 0.9984466433525085),
 ('soil', 0.9984269738197327),
 ('plants', 0.9984176754951477)]

【问题讨论】:

    标签: python doc2vec


    【解决方案1】:

    Doc2Vec 模型收集其 doc-vectors 以供以后在属性 .docvecs 中查找或搜索。要获得 doc-vector 结果,您将在该属性上执行 most_similar()。如果您的Doc2Vec 实例保存在变量d2v_model 中,并且doc_id 保存了训练中已知的文档标签之一,则可能是:

    d2v_model.docvecs.most_similar(doc_id)
    

    如果您要为新文档推断向量,并查找与该推断向量相似的训练文档,您的代码可能如下所示:

    new_dv = d2v_model.infer_vector('some new document'.split())
    d2v_model.docvecs.most_similar(positive=[new_dv])
    

    (Doc2Vec 模型类派生自非常相似的Word2Vec 类,因此继承了most_similar(),默认情况下它只参考内部词向量。这些词向量可能有用,在某些情况下Doc2Vec 模式或随机模式 - 但最好使用 d2v_model.wv.most_similar()d2v_model.docvecs.most_similar() 以明确。)

    基本的Doc2Vec 示例,例如在docs/notebooks 目录doc2vec-lee.ipynb 中安装gensim 的笔记本,包含有用的示例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-10
      • 1970-01-01
      • 2017-08-14
      • 1970-01-01
      • 2018-08-30
      • 2018-08-29
      • 1970-01-01
      • 2018-10-27
      相关资源
      最近更新 更多