释义挖掘
释义挖掘是在大型句子语料库中查找释义(含义相同/相似的文本)的任务。在语义文本相似度中,我们看到了在一个句子列表中查找释义的简化版本。那里介绍的方法使用暴力方法来评分和排序所有对。
但是,由于这具有二次运行时,因此它无法扩展到大型(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]] [source]
给定句子/文本列表,此函数执行释义挖掘。它将所有句子与所有其他句子进行比较,并返回具有最高余弦相似度得分的对的列表。
- 参数:
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_size
和 corpus_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) 之类的条目。