首页 > 解决方案 > 为什么 doc2vec 中最相似的 Gensim 给出与输出相同的向量?

问题描述

我正在使用以下代码来获取用户帖子的有序列表。

model = doc2vec.Doc2Vec.load(doc2vec_model_name)
doc_vectors = model.docvecs.doctag_syn0
doc_tags = model.docvecs.offset2doctag

for w, sim in model.docvecs.most_similar(positive=[model.infer_vector('phone_comments')], topn=4000):
        print(w, sim)
        fw.write(w)
        fw.write(" (")
        fw.write(str(sim))
        fw.write(")")
        fw.write("\n")

fw.close()

但是,我也得到"phone comments"了列表中第 6 位的向量(用于查找最近的邻居)。我在代码中有什么错误吗?还是 Gensim 中的一个问题(因为向量不能是它自己的邻居)?

编辑

Doc2vec模型训练代码

######Preprocessing
docs = []
analyzedDocument = namedtuple('AnalyzedDocument', 'words tags')
for key, value in my_d.items():
    value = re.sub("[^1-9a-zA-Z]"," ", value)
    words = value.lower().split()
    tags = key.replace(' ', '_')
    docs.append(analyzedDocument(words, tags.split(' ')))

sentences = []  # Initialize an empty list of sentences
######Get n-grams
#Get list of lists of tokenised words. 1 sentence = 1 list
for item in docs:
    sentences.append(item.words)

#identify bigrams and trigrams (trigram_sentences_project) 
trigram_sentences_project = []
bigram = Phrases(sentences, min_count=5, delimiter=b' ')
trigram = Phrases(bigram[sentences], min_count=5, delimiter=b' ')

for sent in sentences:
    bigrams_ = bigram[sent]
    trigrams_ = trigram[bigram[sent]]
    trigram_sentences_project.append(trigrams_)

paper_count = 0
for item in trigram_sentences_project:
    docs[paper_count] = docs[paper_count]._replace(words=item)
    paper_count = paper_count+1

# Train model
model = doc2vec.Doc2Vec(docs, size = 100, window = 300, min_count = 5, workers = 4, iter = 20)

#Save the trained model for later use to take the similarity values
model_name = user_defined_doc2vec_model_name
model.save(model_name)

标签: nlpdata-mininggensimword2vecdoc2vec

解决方案


infer_vector()方法需要一个令牌列表,就像用于训练模型words的文本示例(通常是对象)的属性一样。TaggedDocument

您正在提供一个简单的字符串 ,'phone_comments'它看起来infer_vector()像 list ['p', 'h', 'o', 'n', 'e', '_', 'c', 'o', 'm', 'm', 'e', 'n', 't', 's']。因此,您的原始向量most_similar()可能是垃圾。

此外,您没有取回 input 'phone_comments',而是取回了不同的 string 'phone comments'。如果这是模型中的标签名称,那么它一定是tag在模型训练期间提供的。它表面上的相似性phone_comments可能毫无意义——它们是不同的字符串。

(但它也可能暗示你的训练也有问题,而是训练了本应如此的文本words=['phone', 'comments']words=['p', 'h', 'o', 'n', 'e', ' ', 'c', 'o', 'm', 'm', 'e', 'n', 't', 's']


推荐阅读