【问题标题】:Use Spacy to find most similar sentences in doc使用 Spacy 在 doc 中查找最相似的句子
【发布时间】:2019-05-15 13:33:38
【问题描述】:

我正在寻找一种解决方案,以使用 Gensim 中的 most_similar() 之类的东西,但使用 Spacy。 我想使用 NLP 在句子列表中找到最相似的句子。

我尝试将similarity()从Spacy(例如https://spacy.io/api/doc#similarity)一个一个循环使用,但是需要很长时间。

更深入:

我想将所有这些句子放在一个图表中(如this)以查找句子簇。

有什么想法吗?

【问题讨论】:

标签: gensim similarity spacy doc2vec sentence-similarity


【解决方案1】:

这是一个简单的内置解决方案,您可以使用:

import spacy

nlp = spacy.load("en_core_web_lg")
text = (
    "Semantic similarity is a metric defined over a set of documents or terms, where the idea of distance between items is based on the likeness of their meaning or semantic content as opposed to lexicographical similarity."
    " These are mathematical tools used to estimate the strength of the semantic relationship between units of language, concepts or instances, through a numerical description obtained according to the comparison of information supporting their meaning or describing their nature."
    " The term semantic similarity is often confused with semantic relatedness."
    " Semantic relatedness includes any relation between two terms, while semantic similarity only includes 'is a' relations."
    " My favorite fruit is apples."
)
doc = nlp(text)
max_similarity = 0.0
most_similar = None, None
for i, sent in enumerate(doc.sents):
    for j, other in enumerate(doc.sents):
        if j <= i:
            continue
        similarity = sent.similarity(other)
        if similarity > max_similarity:
            max_similarity = similarity
            most_similar = sent, other
print("Most similar sentences are:")
print(f"-> '{most_similar[0]}'")
print("and")
print(f"-> '{most_similar[1]}'")
print(f"with a similarity of {max_similarity}")

(来自wikipedia的文字)

它将产生以下输出:

Most similar sentences are:
-> 'Semantic similarity is a metric defined over a set of documents or terms, where the idea of distance between items is based on the likeness of their meaning or semantic content as opposed to lexicographical similarity.'
and
-> 'These are mathematical tools used to estimate the strength of the semantic relationship between units of language, concepts or instances, through a numerical description obtained according to the comparison of information supporting their meaning or describing their nature.'
with a similarity of 0.9583859443664551

注意来自spacy.io的以下信息:

为了使它们紧凑和快速,spaCy 的小型管道包(所有以 sm 结尾的包)不附带词向量,只包含上下文相关的张量。这意味着您仍然可以使用similarity() 方法来比较文档、跨度和标记——但结果不会那么好,并且单个标记不会分配任何向量。所以为了使用真实的词向量,你需要下载一个更大的管道包:

- python -m spacy download en_core_web_sm
+ python -m spacy download en_core_web_lg

另请参阅Document similarity in Spacy vs Word2Vec,了解有关如何提高相似度分数的建议。

【讨论】:

  • 那是 2 年前的事了,我已经不在了。但我做了类似的事情,问题可能出在实现中:我猜 gensim 最相似的用途是多线程优化。使用这个循环解决方案,它太线性了,并且计算时间随着语料库的长而增长非常快。使用光照模型可能是一个很好的解决方案。
猜你喜欢
  • 1970-01-01
  • 2020-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-15
  • 2011-05-11
  • 2021-10-08
  • 2019-02-06
相关资源
最近更新 更多