跳到内容

相似性

pipeline pipeline

相似性管道使用文本分类器计算查询与文本列表之间的相似性。

此管道支持标准文本分类模型和零样本分类模型。管道使用查询作为输入文本的标签。结果被转置以获得每个查询/标签的分数 vs 每个输入文本的分数。

通过 crossencode=True 构造函数参数支持 Cross-encoder 模型。这些模型通过 CrossEncoder 管道加载,该管道也可以直接实例化。CrossEncoder 管道具有与下文描述相同的方法和功能。

示例

以下显示了使用此管道的简单示例。

from txtai.pipeline import Similarity

# Create and run pipeline
similarity = Similarity()
similarity("feel good story", [
    "Maine man wins $1M from $25 lottery ticket", 
    "Don't sacrifice slower friends in a bear attack"
])

有关更详细的示例,请参阅下方链接。

笔记本 描述
将语义搜索添加到 Elasticsearch 将语义搜索添加到现有搜索系统 Open In Colab

配置驱动的示例

管道使用 Python 或配置运行。可以使用管道的小写名称在配置中实例化管道。配置驱动的管道使用工作流API运行。

config.yml

# Create pipeline using lower case class name
similarity:

使用工作流运行

from txtai import Application

# Create and run pipeline with workflow
app = Application("config.yml")
app.similarity("feel good story", [
    "Maine man wins $1M from $25 lottery ticket", 
    "Don't sacrifice slower friends in a bear attack"
])

使用 API 运行

CONFIG=config.yml uvicorn "txtai.api:app" &

curl \
  -X POST "http://localhost:8000/similarity" \
  -H "Content-Type: application/json" \
  -d '{"query": "feel good story", "texts": ["Maine man wins $1M from $25 lottery ticket", "Dont sacrifice slower friends in a bear attack"]}'

方法

该管道的 Python 文档。

__init__(path=None, quantize=False, gpu=True, model=None, dynamic=True, crossencode=False, **kwargs)

源代码位于 txtai/pipeline/text/similarity.py
16
17
18
19
20
21
def __init__(self, path=None, quantize=False, gpu=True, model=None, dynamic=True, crossencode=False, **kwargs):
    # Use zero-shot classification if dynamic is True and crossencode is False, otherwise use standard text classification
    super().__init__(path, quantize, gpu, model, False if crossencode else dynamic, **kwargs)

    # Load as a cross-encoder if crossencode set to True
    self.crossencoder = CrossEncoder(model=self.pipeline) if crossencode else None

__call__(query, texts, multilabel=True, **kwargs)

计算查询与文本列表之间的相似性。返回一个按最高得分排序的 (id, score) 列表,其中 id 是文本列表中的索引。

此方法支持字符串或列表形式的查询。如果输入是字符串,则返回类型是一个一维的 (id, score) 列表。如果文本是列表,则返回一个二维的 (id, score) 列表,每行对应一个字符串。

参数

名称 类型 描述 默认值
query

查询文本|列表

必需
texts

文本列表

必需
multilabel

如果为 True,标签是独立的;如果为 False,分数会按每个文本项归一化,使其总和为 1;如果为 None,返回原始分数

True
kwargs

附加关键字参数

{}

返回值

类型 描述

(id, score) 列表

源代码位于 txtai/pipeline/text/similarity.py
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
def __call__(self, query, texts, multilabel=True, **kwargs):
    """
    Computes the similarity between query and list of text. Returns a list of
    (id, score) sorted by highest score, where id is the index in texts.

    This method supports query as a string or a list. If the input is a string,
    the return type is a 1D list of (id, score). If text is a list, a 2D list
    of (id, score) is returned with a row per string.

    Args:
        query: query text|list
        texts: list of text
        multilabel: labels are independent if True, scores are normalized to sum to 1 per text item if False, raw scores returned if None
        kwargs: additional keyword args

    Returns:
        list of (id, score)
    """

    if self.crossencoder:
        # pylint: disable=E1102
        return self.crossencoder(query, texts, multilabel)

    # Call Labels pipeline for texts using input query as the candidate label
    scores = super().__call__(texts, [query] if isinstance(query, str) else query, multilabel, **kwargs)

    # Sort on query index id
    scores = [[score for _, score in sorted(row)] for row in scores]

    # Transpose axes to get a list of text scores for each query
    scores = np.array(scores).T.tolist()

    # Build list of (id, score) per query sorted by highest score
    scores = [sorted(enumerate(row), key=lambda x: x[1], reverse=True) for row in scores]

    return scores[0] if isinstance(query, str) else scores