释义挖掘

释义挖掘是在大型句子语料库中查找释义(含义相同/相似的文本)的任务。在语义文本相似度中,我们看到了在句子列表中查找释义的简化版本。那里提出的方法使用暴力方法来评分和排序所有对。

然而,由于这具有二次运行时,因此它无法扩展到大型(10,000 个及以上)句子集合。paraphrase_mining()函数可用于更大的集合

from sentence_transformers import SentenceTransformer
from sentence_transformers.util import paraphrase_mining

model = SentenceTransformer("all-MiniLM-L6-v2")

# Single list of sentences - Possible tens of thousands of sentences
sentences = [
    "The cat sits outside",
    "A man is playing guitar",
    "I love pasta",
    "The new movie is awesome",
    "The cat plays in the garden",
    "A woman watches TV",
    "The new movie is so great",
    "Do you like pizza?",
]

paraphrases = paraphrase_mining(model, sentences)

for paraphrase in paraphrases[0:10]:
    score, i, j = paraphrase
    print("{} \t\t {} \t\t Score: {:.4f}".format(sentences[i], sentences[j], score))

paraphrase_mining() 接受以下参数

sentence_transformers.util.paraphrase_mining(model, sentences: list[str], show_progress_bar: bool = False, batch_size: int = 32, query_chunk_size: int = 5000, corpus_chunk_size: int = 100000, max_pairs: int = 500000, top_k: int = 100, score_function: ~typing.Callable[[~torch.Tensor, ~torch.Tensor], ~torch.Tensor] = <function cos_sim>) list[list[float | int]][来源]

给定句子/文本列表,此函数执行释义挖掘。它将所有句子与所有其他句子进行比较,并返回具有最高余弦相似度分数的句子对列表。

参数:
  • model (SentenceTransformer) – 用于嵌入计算的 SentenceTransformer 模型

  • sentences (List[str]) – 字符串(文本或句子)列表

  • show_progress_bar (bool, optional) – 进度条的绘制。默认为 False。

  • batch_size (int, optional) – 模型同时编码的文本数量。默认为 32。

  • query_chunk_size (int, optional) – 同时搜索 #query_chunk_size 的最相似对。减少此值可降低内存占用(增加运行时间)。默认为 5000。

  • corpus_chunk_size (int, optional) – 将一个句子同时与 #corpus_chunk_size 个其他句子进行比较。减少此值可降低内存占用(增加运行时间)。默认为 100000。

  • max_pairs (int, optional) – 返回的最大文本对数。默认为 500000。

  • top_k (int, optional) – 对于每个句子,我们最多检索 top_k 个其他句子。默认为 100。

  • score_function (Callable[[Tensor, Tensor], Tensor], optional) – 用于计算分数的函数。默认情况下为余弦相似度。默认为 cos_sim。

返回:

返回格式为 [score, id1, id2] 的三元组列表

返回类型:

List[List[Union[float, int]]]

为了优化内存和计算时间,释义挖掘以块为单位执行,由 query_chunk_sizecorpus_chunk_size 指定。具体来说,一次只比较 query_chunk_size * corpus_chunk_size 对,而不是 len(sentences) * len(sentences) 对。这更省时省内存。此外,paraphrase_mining() 只考虑每个句子每个块的 top_k 最佳分数。您可以尝试使用此值来权衡效率和性能。

例如,对于每个句子,您将在此脚本中仅获得一个最相关的句子。

paraphrases = paraphrase_mining(model, sentences, corpus_chunk_size=len(sentences), top_k=1)

最后一个关键参数是 max_pairs,它确定函数返回的最大释义对数。通常,您获得的返回对数较少,因为列表已清除重复项,例如,如果它包含 (A, B) 和 (B, A),则仅返回一个。

注意

如果 B 是 A 最相似的句子,则 A 不一定是 B 最相似的句子。因此,可能会出现返回的列表包含类似 (A, B) 和 (B, C) 的条目的情况。