跳到内容

上下文精度

上下文精度 (Context Precision) 是一个衡量 retrieved_contexts 中相关块比例的指标。它的计算方法是上下文中的每个块的 precision@k 的平均值。Precision@k 是在排名 k 处的相关块数量与排名 k 处的块总数的比率。

\[ \text{Context Precision@K} = \frac{\sum_{k=1}^{K} \left( \text{Precision@k} \times v_k \right)}{\text{前 K 个结果中的相关项总数}} \]
\[ \text{精确率@k} = {\text{真阳性@k} \over (\text{真阳性@k} + \text{假阳性@k})} \]

其中 \(K\)retrieved_contexts 中的总块数,且 \(v_k \in \{0, 1\}\) 是排名 \(k\) 处的相关性指示器。

基于 LLM 的上下文精度

以下指标使用大型语言模型 (LLM) 来判断检索到的上下文是否相关。

无参考的上下文精度

当您对某个 user_input 同时拥有检索到的上下文和参考上下文时,可以使用 LLMContextPrecisionWithoutReference 指标。为了判断检索到的上下文是否相关,此方法使用 LLM 将 retrieved_contexts 中存在的每个检索到的上下文或块与 response 进行比较。

示例

from ragas import SingleTurnSample
from ragas.metrics import LLMContextPrecisionWithoutReference

context_precision = LLMContextPrecisionWithoutReference(llm=evaluator_llm)

sample = SingleTurnSample(
    user_input="Where is the Eiffel Tower located?",
    response="The Eiffel Tower is located in Paris.",
    retrieved_contexts=["The Eiffel Tower is located in Paris."], 
)


await context_precision.single_turn_ascore(sample)
输出
0.9999999999

有参考的上下文精度

当您对某个 user_input 同时拥有检索到的上下文和参考答案时,可以使用 LLMContextPrecisionWithReference 指标。为了判断检索到的上下文是否相关,此方法使用 LLM 将 retrieved_contexts 中存在的每个检索到的上下文或块与 reference 进行比较。

示例

from ragas import SingleTurnSample
from ragas.metrics import LLMContextPrecisionWithReference

context_precision = LLMContextPrecisionWithReference(llm=evaluator_llm)

sample = SingleTurnSample(
    user_input="Where is the Eiffel Tower located?",
    reference="The Eiffel Tower is located in Paris.",
    retrieved_contexts=["The Eiffel Tower is located in Paris."], 
)

await context_precision.single_turn_ascore(sample)
输出
0.9999999999

非基于 LLM 的上下文精度

该指标使用传统方法来判断检索到的上下文是否相关。它依赖非 LLM 的指标作为距离度量来评估检索到的上下文的相关性。

基于参考上下文的上下文精度

NonLLMContextPrecisionWithReference 指标设计用于对某个 user_input 同时拥有检索到的上下文和参考上下文的场景。为了判断检索到的上下文是否相关,此方法使用非 LLM 的相似性度量将 retrieved_contexts 中的每个检索到的上下文或块与 reference_contexts 中的每个上下文进行比较。

示例

from ragas import SingleTurnSample
from ragas.metrics import NonLLMContextPrecisionWithReference

context_precision = NonLLMContextPrecisionWithReference()

sample = SingleTurnSample(
    retrieved_contexts=["The Eiffel Tower is located in Paris."], 
    reference_contexts=["Paris is the capital of France.", "The Eiffel Tower is one of the most famous landmarks in Paris."]
)

await context_precision.single_turn_ascore(sample)
输出
0.9999999999