gpt4 book ai didi

python - Doc2Vec找到相似的句子

转载 作者:行者123 更新时间:2023-12-01 00:30:40 24 4
gpt4 key购买 nike

我正在尝试使用 doc2vec 找到类似的句子。我找不到与训练的句子相匹配的实际句子。

下面是来自 this article 的代码:

from gensim.models.doc2vec import Doc2Vec, TaggedDocument
from nltk.tokenize import word_tokenize
data = ["I love machine learning. Its awesome.",
"I love coding in python",
"I love building chatbots",
"they chat amagingly well"]

tagged_data = [TaggedDocument(words=word_tokenize(_d.lower()), tags=[str(i)]) for i, _d in enumerate(data)]
max_epochs = 100
vec_size = 20
alpha = 0.025

model = Doc2Vec(size=vec_size,
alpha=alpha,
min_alpha=0.00025,
min_count=1,
dm =1)

model.build_vocab(tagged_data)

for epoch in range(max_epochs):
print('iteration {0}'.format(epoch))
model.train(tagged_data,
total_examples=model.corpus_count,
epochs=model.iter)
# decrease the learning rate
model.alpha -= 0.0002
# fix the learning rate, no decay
model.min_alpha = model.alpha

model.save("d2v.model")
print("Model Saved")

model= Doc2Vec.load("d2v.model")
#to find the vector of a document which is not in training data
test_data = word_tokenize("I love building chatbots".lower())
v1 = model.infer_vector(test_data)
print("V1_infer", v1)

# to find most similar doc using tags
similar_doc = model.docvecs.most_similar('1')
print(similar_doc)


# to find vector of doc in training data using tags or in other words, printing the vector of document at index 1 in training data
print(model.docvecs['1'])

但是上面的代码只给我向量或数字。但我怎样才能从训练数据中得到匹配的实际句子呢?例如 - 在这种情况下,我期望结果为“我喜欢构建聊天机器人”。

最佳答案

similar_doc的输出是:[('2', 0.991769552230835), ('0', 0.989276111125946), ('3', 0.9854298830032349)]

这显示了 data 中每个文档的相似度得分与请求的文档一起,并按降序排序。

以此为基础,'2' indexdata是最接近请求的数据,即 test_data .

print(data[int(similar_doc[0][0])])
// prints: I love building chatbots

注意:此代码每次都会给出不同的结果,也许您需要更好的模型或更多的训练数据。

关于python - Doc2Vec找到相似的句子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58206571/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com