【问题标题】:How to find the score for sentence Similarity using Word2Vec如何使用 Word2Vec 找到句子相似度的分数
【发布时间】:2019-06-30 01:02:13
【问题描述】:

我是 NLP 新手,如何找到 2 个句子之间的相似性以及如何打印每个单词的分数。以及如何实现gensim word2Vec模型。

试试这个代码: 这是我的两句话:

sentence1="I am going to India"
sentence2=" I am going to Bharat"
from gensim.models import word2vec
import numpy as np


words1 = sentence1.split(' ')
words2 = sentence2.split(' ')

#The meaning of the sentence can be interpreted as the average of its words
sentence1_meaning = word2vec(words1[0])
count = 1
for w in words1[1:]:
    sentence1_meaning = np.add(sentence1_meaning, word2vec(w))
    count += 1
sentence1_meaning /= count

sentence2_meaning = word2vec(words2[0])
count = 1
for w in words2[1:]:
    sentence2_meaning = np.add(sentence2_meaning, word2vec(w))
    count += 1
sentence2_meaning /= count

#Similarity is the cosine between the vectors
similarity = np.dot(sentence1_meaning, sentence2_meaning)/(np.linalg.norm(sentence1_meaning)*np.linalg.norm(sentence2_meaning))

【问题讨论】:

标签: nlp gensim word2vec


【解决方案1】:

您可以训练模型并使用相似度函数得到两个单词之间的余弦相似度。

这是一个简单的演示:

from gensim.models import Word2Vec
from gensim.test.utils import common_texts

model = Word2Vec(common_texts, 
                 size = 500, 
                 window = 5, 
                 min_count = 1, 
                 workers = 4)

word_vectors = model.wv

word_vectors.similarity('computer', 'computer')

输出当然是1.0,表示100%相似度。

【讨论】:

    【解决方案2】:

    在您的from gensim.models import word2vec 之后,word2vec 是一个 Python 模块 - 不是一个您可以调用为 word2vec(words1[0])word2vec(w) 的函数。

    因此,您的代码甚至无法正确处理此问题,您应该查看演示正确使用 gensim Word2Vec 类和支持方法的文档/教程,然后模仿这些方法。

    正如@david-dale 提到的,gensim 文档中有一个基本介绍,用于Word2Vec

    https://radimrehurek.com/gensim/models/word2vec.html

    gensim 库还在其docs/notebooks 目录中捆绑了许多演示各种算法和技术的 Jupyter 笔记本。笔记本word2vec.ipynb 显示基本的Word2Vec 用法;您也可以通过项目的源代码存储库查看它...

    https://github.com/RaRe-Technologies/gensim/blob/develop/docs/notebooks/word2vec.ipynb

    ...但是,最好作为本地笔记本运行,这样您就可以逐个单元地执行执行,并自己尝试不同的变体,甚至可以调整它以使用您的数据。

    当您达到该级别时,请注意:

    • 这些模型需要的不仅仅是几个句子作为训练——所以理想情况下,您要么拥有 (a) 与您正在比较的句子来自同一领域的许多句子,这样模型就可以在那些背景; (b) 从兼容语料库训练的模型,然后将其应用于您的语料库外句子。

    • 使用句子中所有词向量的平均值只是为较长文本制作向量的一种相对简单的方法;还有许多其他更复杂的方法。与Word2Vec 非常相似的一种替代方法是“段落向量”算法,它也可以在gensim 中作为Doc2Vec 类使用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-28
      • 2016-07-10
      • 2015-01-23
      • 2021-05-07
      • 2014-04-03
      • 2018-02-02
      • 2017-12-25
      • 1970-01-01
      相关资源
      最近更新 更多