114 深入解析`QueryFusionRetriever`类中的相对评分融合方法 llamaindex.core.retrievers

深入解析QueryFusionRetriever类中的相对评分融合方法

在信息检索系统中,如何有效地融合多个检索器的输出结果是一个关键问题。QueryFusionRetriever类提供了_relative_score_fusion方法,用于应用相对评分融合技术。本文将详细解析该方法,帮助您更好地理解其工作原理及实际应用。

前置知识

在深入代码之前,我们需要了解以下几个关键概念:

  1. 相对评分融合:一种用于融合多个检索器结果的算法,通过将每个检索器的评分进行归一化处理,然后根据检索器的权重进行加权融合。
  2. 归一化(Normalization):将数据按比例缩放,使之落入一个小的特定区间,如[0, 1]。
  3. 检索器权重(Retriever Weight):表示每个检索器在融合过程中的重要性。

代码解析

_relative_score_fusion方法

def _relative_score_fusion(
        self,
        results: Dict[Tuple[str, int], List[NodeWithScore]],
        dist_based: Optional[bool] = False,
    ) -> List[NodeWithScore]:
    """Apply relative score fusion."""
    # MinMax scale scores of each result set (highest value becomes 1, lowest becomes 0)
    # then scale by the weight of the retriever
    min_max_scores = {}
    for query_tuple, nodes_with_scores in results.items():
        if not nodes_with_scores:
            min_max_scores[query_tuple] = (0.0, 0.0)
            continue
        scores = [node_with_score.score for node_with_score in nodes_with_scores]
        if dist_based:
            # Set min and max based on mean and std dev
            mean_score = sum(scores) / len(scores)
            std_dev = (
                sum((x - mean_score) ** 2 for x in scores) / len(scores)
            ) ** 0.5
            min_score = mean_score - 3 * std_dev
            max_score = mean_score + 3 * std_dev
        else:
            min_score = min(scores)
            max_score = max(scores)
        min_max_scores[query_tuple] = (min_score, max_score)

    for query_tuple, nodes_with_scores in results.items():
        for node_with_score in nodes_with_scores:
            min_score, max_score = min_max_scores[query_tuple]
            # Scale the score to be between 0 and 1
            if max_score == min_score:
                node_with_score.score = 1.0 if max_score > 0 else 0.0
            else:
                node_with_score.score = (node_with_score.score - min_score) / (
                    max_score - min_score
                )
            # Scale by the weight of the retriever
            retriever_idx = query_tuple[1]
            node_with_score.score *= self._retriever_weights[retriever_idx]
            # Divide by the number of queries
            node_with_score.score /= self.num_queries

    # Use a dict to de-duplicate nodes
    all_nodes: Dict[str, NodeWithScore] = {}

    # Sum scores for each node
    for nodes_with_scores in results.values():
        for node_with_score in nodes_with_scores:
            hash = node_with_score.node.hash
            if hash in all_nodes:
                all_nodes[hash].score += node_with_score.score
            else:
                all_nodes[hash] = node_with_score

    return sorted(all_nodes.values(), key=lambda x: x.score or 0.0, reverse=True)
方法解析
  • 功能:该方法应用相对评分融合技术,对多个检索器的输出结果进行重新排序。
  • 参数results,一个字典,键为(str, int)元组,值为NodeWithScore列表,表示每个检索器的输出结果;dist_based,一个可选参数,表示是否基于分布进行归一化。
  • 返回值:一个包含重新排序后的NodeWithScore实例的列表。
处理流程
  1. 初始化最小最大评分字典

    min_max_scores = {}
    

    min_max_scores用于存储每个检索器输出结果的最小和最大评分。

  2. 计算每个检索器输出结果的最小和最大评分

    for query_tuple, nodes_with_scores in results.items():
        if not nodes_with_scores:
            min_max_scores[query_tuple] = (0.0, 0.0)
            continue
        scores = [node_with_score.score for node_with_score in nodes_with_scores]
        if dist_based:
            mean_score = sum(scores) / len(scores)
            std_dev = (
                sum((x - mean_score) ** 2 for x in scores) / len(scores)
            ) ** 0.5
            min_score = mean_score - 3 * std_dev
            max_score = mean_score + 3 * std_dev
        else:
            min_score = min(scores)
            max_score = max(scores)
        min_max_scores[query_tuple] = (min_score, max_score)
    

    遍历每个检索器的输出结果,计算其评分列表的最小和最大值,并存储到min_max_scores中。如果dist_basedTrue,则基于均值和标准差计算最小和最大值。

  3. 归一化评分并加权

    for query_tuple, nodes_with_scores in results.items():
        for node_with_score in nodes_with_scores:
            min_score, max_score = min_max_scores[query_tuple]
            if max_score == min_score:
                node_with_score.score = 1.0 if max_score > 0 else 0.0
            else:
                node_with_score.score = (node_with_score.score - min_score) / (
                    max_score - min_score
                )
            retriever_idx = query_tuple[1]
            node_with_score.score *= self._retriever_weights[retriever_idx]
            node_with_score.score /= self.num_queries
    

    遍历每个检索器的输出结果,将其评分归一化到[0, 1]区间,然后根据检索器的权重进行加权,并除以查询数量。

  4. 去重并累加评分

    all_nodes: Dict[str, NodeWithScore] = {}
    for nodes_with_scores in results.values():
        for node_with_score in nodes_with_scores:
            hash = node_with_score.node.hash
            if hash in all_nodes:
                all_nodes[hash].score += node_with_score.score
            else:
                all_nodes[hash] = node_with_score
    

    使用字典all_nodes去重节点,并累加每个节点的评分。

  5. 排序结果

    return sorted(all_nodes.values(), key=lambda x: x.score or 0.0, reverse=True)
    

    将融合后的节点按评分降序排序,并返回结果。

实际应用示例

假设我们有多个检索器的输出结果,需要应用相对评分融合技术进行重新排序:

from some_module import QueryFusionRetriever, NodeWithScore

# 初始化QueryFusionRetriever实例
fusion_retriever = QueryFusionRetriever(...)

# 假设我们有多个检索器的输出结果
results = {
    ("retriever1", 0): [NodeWithScore(node=..., score=0.8), NodeWithScore(node=..., score=0.7)],
    ("retriever2", 1): [NodeWithScore(node=..., score=0.9), NodeWithScore(node=..., score=0.6)],
}

# 应用相对评分融合技术
reranked_results = fusion_retriever._relative_score_fusion(results)

# 输出生成的查询
for node_with_score in reranked_results:
    print(f"Node: {node_with_score.node}, Score: {node_with_score.score}")

总结

通过本文的详细解析,我们深入理解了QueryFusionRetriever类中相对评分融合方法的实现原理和应用方法。该方法通过将每个检索器的评分进行归一化处理,然后根据检索器的权重进行加权融合,有效地融合多个检索器的输出结果,从而提升检索系统的准确性和全面性。希望本文能为您的编程实践提供有益的参考和帮助。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

需要重新演唱

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值