高级RAG:使用RAGAs + LlamaIndex进行RAG评估,包括原理、图和代码

news2024/10/6 14:27:37

原文地址:Using RAGAs + LlamaIndex for RAG evaluation

2024 年 2 月 5 日

如果您已经为实际的业务系统开发了检索增强生成(Retrieval Augmented Generation, RAG)应用程序,那么您可能会关心它的有效性。换句话说,您想要评估RAG的性能。

此外,如果您发现您现有的RAG不够有效,您可能需要验证先进的RAG改进方法的有效性。换句话说,您需要进行评估,看看这些改进方法是否有效。

在本文中,我们首先介绍了由RAGAs(检索增强生成评估)提出的RAG的评估指标,这是一个用于评估RAG管道的框架。然后,我们解释了如何使用RAGAs + LlamaIndex实现整个评估过程。

RAG评价指标

简单地说,RAG的过程包括三个主要部分:输入查询、检索上下文和LLM生成的响应。这三个要素构成了RAG过程中最重要的三位一体,并且是相互依存的。

因此,可以通过测量这些三元组之间的相关性来评估RAG的有效性,如图1所示。

img

图1:RAG的有效性可以通过测量这些三元组之间的相关性来评估。

论文总共提到了3个指标:忠实度、答案相关性和上下文相关性,这些指标不需要访问人工注释的数据集或参考答案。

此外,RAGAs网站引入了另外两个指标:上下文精度和上下文召回。

Faithfulness/Groundedness

Faithfulness指的是确保答案是基于给定的上下文。这对于避免错觉和确保检索到的上下文可以用作生成答案的理由非常重要。

如果分数低,则表明LLM的回答不符合检索到的知识,提供幻觉答案的可能性增加。例如:

img

图2:高Faithfulness答案和低Faithfulness答案。来源:https://docs.ragas.io/en/latest/concepts/metrics/faithfulness.html。

为了估计信度,我们首先使用LLM提取一组语句,**S(a(q))**。方法是使用以下prompt:

1
2
3
Given a question and answer, create one or more statements from each sentence in the given answer.
question: [question]
answer: [answer]

在生成**S(a(q))之后,LLM确定是否可以从c(q)**中推断出每个语句si。此验证步骤使用以下prompt执行:

1
2
3
4
5
Consider the given context and following statements, then determine whether they are supported by the information present in the context. Provide a brief explan ation for each statement before arriving at the verdict (Yes/No). Provide a final verdict for each statement in order at the end in the given format. Do not deviate from the specified format.

statement: [statement 1]
...
statement: [statement n]

最终的忠实度得分**F计算为 F = |V|/|S|** ,其中**|V|表示根据LLM支持的语句数,|S|**表示语句总数。

回答的相关性

这个度量度量生成的答案和查询之间的相关性。分数越高,相关性越好。例如:

img

图3:高相关性答案和低相关性答案。来源:https://docs.ragas.io/en/latest/concepts/metrics/answer_relevance.html。

为了估计答案的相关性,我们promptLLM根据给定的答案 a(q) 生成n个潜在问题 qi ,如下所示:

1
2
3
Generate a question for the given answer.

answer: [answer]

然后,我们利用文本Embedding模型获得所有问题的Embeddings。

对于每个 qi ,我们计算 sim(q, qi) 与原始问题 q 的相似性。这对应于Embeddings之间的余弦相似度。问题**q的答案相关性评分AR**计算方法如下:

img

上下文相关性

这是一个度量检索质量的指标,主要评估检索上下文支持查询的程度。分数低表明检索到的不相关内容数量较多,这可能会影响LLM生成的最终答案。例如:

img

图4:高上下文相关性和低上下文相关性。来源:https://docs.ragas.io/en/latest/concepts/metrics/context_relevancy.html。

为了估计上下文的相关性,使用LLM从上下文**(c(q))**中提取一组关键句子 (Sext) 。这些句子对于回答这个问题至关重要。prompt符如下:

1
2
3
4
Please extract relevant sentences from the provided context that can potentially help answer the following question. 
If no relevant sentences are found, or if you believe the question cannot be answered from the given context, 
return the phrase "Insufficient Information". 
While extracting candidate sentences you’re not allowed to make any changes to sentences from given context.

然后,在RAGAs中,使用以下公式在句子级别计算相关性:

img

上下文召回

该度量度量检索上下文与带注释的答案之间的一致性级别。它是使用地面真值和检索上下文计算的,值越高表示性能越好。例如:

img

图5:高上下文回忆和低上下文回忆。来源:Context Recall | Ragas

在实施时,要求提供地面真值数据。

计算公式如下:

img

上下文精准度

这个度量是相对复杂的,它被用来度量包含真实事实的所有相关上下文是否都排在最前面。分数越高表示精确度越高。

该指标的计算公式如下:

img

上下文精确的优势在于它能够感知排序效应。但是,它的缺点是,如果相关的召回很少,但是排名都很高,那么得分也会很高。因此,有必要结合其他几个指标来考虑总体效果。

采用RAGAs + LlamaIndex进行RAG评价

主要流程如图6所示:

img

图6:主流程。

环境配置

安装ragas: pip install ragas。然后,检查当前版本。

1
2
(py) Florian:~ Florian$ pip list | grep ragas
ragas                        0.0.22

值得一提的是,如果您使用pip install git+https://github.com/explodinggradients/ragas.git安装最新版本(v0.1.0rc1),则不支持LlamaIndex。

然后导入相关库,设置环境变量和全局变量

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import os
os.environ["OPENAI_API_KEY"] = "YOUR_OPENAI_KEY"
dir_path = "YOUR_DIR_PATH"

from llama_index import VectorStoreIndex, SimpleDirectoryReader

from ragas.metrics import (
    faithfulness,
    answer_relevancy,
    context_relevancy,
    context_recall,
    context_precision
)

from ragas.llama_index import evaluate

目录中只有一个PDF文件,使用的是论文“TinyLlama:一个开源的小型语言模型”。

1
2
(py) Florian:~ Florian$ ls /Users/Florian/Downloads/pdf_test/
tinyllama.pdf

使用LlamaIndex构建一个简单的RAG查询引擎

1
2
3
documents = SimpleDirectoryReader(dir_path).load_data()
index = VectorStoreIndex.from_documents(documents)
query_engine = index.as_query_engine()

LlamaIndex默认使用OpenAI模型,LLM和Embedding模型可以通过ServiceContext轻松配置。

构建评估数据集

由于有些指标需要手动标注数据集,所以我自己编写了一些问题和相应的答案。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
eval_questions = [
    "Can you provide a concise description of the TinyLlama model?",
    "I would like to know the speed optimizations that TinyLlama has made.",
    "Why TinyLlama uses Grouped-query Attention?",
    "Is the TinyLlama model open source?",
    "Tell me about starcoderdata dataset",
]
eval_answers = [
    "TinyLlama is a compact 1.1B language model pretrained on around 1 trillion tokens for approximately 3 epochs. Building on the architecture and tokenizer of Llama 2, TinyLlama leverages various advances contributed by the open-source community (e.g., FlashAttention), achieving better computational efficiency. Despite its relatively small size, TinyLlama demonstrates remarkable performance in a series of downstream tasks. It significantly outperforms existing open-source language models with comparable sizes.",
    "During training, our codebase has integrated FSDP to leverage multi-GPU and multi-node setups efficiently. Another critical improvement is the integration of Flash Attention, an optimized attention mechanism. We have replaced the fused SwiGLU module from the xFormers (Lefaudeux et al., 2022) repository with the original SwiGLU module, further enhancing the efficiency of our codebase. With these features, we can reduce the memory footprint, enabling the 1.1B model to fit within 40GB of GPU RAM.",  
    "To reduce memory bandwidth overhead and speed up inference, we use grouped-query attention in our model. We have 32 heads for query attention and use 4 groups of key-value heads. With this technique, the model can share key and value representations across multiple heads without sacrificing much performance",
    "Yes, TinyLlama is open-source",
    "This dataset was collected to train StarCoder (Li et al., 2023), a powerful opensource large code language model. It comprises approximately 250 billion tokens across 86 programming languages. In addition to code, it also includes GitHub issues and text-code pairs that involve natural languages.",
]
eval_answers = [[a] for a in eval_answers]

指标选择和RAGAs评估

1
2
3
4
5
6
7
8
9
10
metrics = [
    faithfulness,
    answer_relevancy,
    context_relevancy,
    context_precision,
    context_recall,
]

result = evaluate(query_engine, metrics, eval_questions, eval_answers)
result.to_pandas().to_csv('YOUR_CSV_PATH', sep=',')

请注意,在缺省情况下,在RAGAs中使用OpenAI模型。

在RAGAs中,如果您想使用另一个LLM(如Gemini)使用LlamaIndex来评估,即使在调试了RAGAs的源代码之后,我也没有在RAGAs版本0.0.22中找到任何有用的方法。

最终代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import os
os.environ["OPENAI_API_KEY"] = "YOUR_OPENAI_KEY"
dir_path = "YOUR_DIR_PATH"

from llama_index import VectorStoreIndex, SimpleDirectoryReader

from ragas.metrics import (
    faithfulness,
    answer_relevancy,
    context_relevancy,
    context_recall,
    context_precision
)

from ragas.llama_index import evaluate

documents = SimpleDirectoryReader(dir_path).load_data()
index = VectorStoreIndex.from_documents(documents)
query_engine = index.as_query_engine()

eval_questions = [
    "Can you provide a concise description of the TinyLlama model?",
    "I would like to know the speed optimizations that TinyLlama has made.",
    "Why TinyLlama uses Grouped-query Attention?",
    "Is the TinyLlama model open source?",
    "Tell me about starcoderdata dataset",
]
eval_answers = [
    "TinyLlama is a compact 1.1B language model pretrained on around 1 trillion tokens for approximately 3 epochs. Building on the architecture and tokenizer of Llama 2, TinyLlama leverages various advances contributed by the open-source community (e.g., FlashAttention), achieving better computational efficiency. Despite its relatively small size, TinyLlama demonstrates remarkable performance in a series of downstream tasks. It significantly outperforms existing open-source language models with comparable sizes.",
    "During training, our codebase has integrated FSDP to leverage multi-GPU and multi-node setups efficiently. Another critical improvement is the integration of Flash Attention, an optimized attention mechanism. We have replaced the fused SwiGLU module from the xFormers (Lefaudeux et al., 2022) repository with the original SwiGLU module, further enhancing the efficiency of our codebase. With these features, we can reduce the memory footprint, enabling the 1.1B model to fit within 40GB of GPU RAM.",  
    "To reduce memory bandwidth overhead and speed up inference, we use grouped-query attention in our model. We have 32 heads for query attention and use 4 groups of key-value heads. With this technique, the model can share key and value representations across multiple heads without sacrificing much performance",
    "Yes, TinyLlama is open-source",
    "This dataset was collected to train StarCoder (Li et al., 2023), a powerful opensource large code language model. It comprises approximately 250 billion tokens across 86 programming languages. In addition to code, it also includes GitHub issues and text-code pairs that involve natural languages.",
]
eval_answers = [[a] for a in eval_answers]

metrics = [
    faithfulness,
    answer_relevancy,
    context_relevancy,
    context_precision,
    context_recall,
]

result = evaluate(query_engine, metrics, eval_questions, eval_answers)
result.to_pandas().to_csv('YOUR_CSV_PATH', sep=',')

请注意,在终端中运行程序时,可能不会完全显示Pandas数据框。为了查看它,您可以将其导出为CSV文件,如图6所示。

img

图6:最终结果。图片来自作者。

从图6中可以明显看出,第四个问题“Tell me about starcoderdata dataset”全部为0。这是因为LLM无法给出答案。第二个和第三个问题的上下文精度为0,表明检索上下文中的相关上下文没有排在最前面。第二个问题的上下文召回为0,表明检索到的上下文与带注释的答案不匹配。

现在,我们来检查问题0至问题3。这些问题的答案相关性得分很高,表明答案和问题之间存在很强的相关性。此外,信度得分不低,这表明答案主要是从上下文推导或总结出来的,可以得出结论,答案不是由于LLM的幻觉而产生的。

此外,我们发现尽管我们的上下文相关性得分很低,gpt-3.5-turbo-16k (RAGAs的默认模型)仍然能够从中推断出答案。

从结果来看,这个基本的RAG系统显然还有很大的改进空间。

结论

一般来说,RAGAs为评估RAG提供了全面的指标,并提供了方便的调用。目前,RAG评价框架缺乏,RAGAs提供了一个有效的工具。

在调试RAGAs的内部源代码后,很明显RAGAs仍处于早期开发阶段。我们对其未来的更新和改进持乐观态度。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1468852.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【大数据】Flink 内存管理(三):TaskManager 内存分配(理论篇)

Flink 内存管理(三):TaskManager 内存分配 1.配置 Total Memory2.配置 Heap and Managed Memory2.1 Task (Operator) Heap Memory2.2 Managed Memory 3.配置 Off-Heap Memory(Direct or Native)4.详细内存模型5.Framew…

现在学Oracle是49年入国军么?

今天周末,不聊技术,聊聊大家说的最多的一个话题 先说明一下,防止挨喷😆 本人并不是职业dba,对数据库就是爱好,偶尔兼职,以下仅个人观点分析,如有不同观点请轻喷,哈哈&…

分享一个我爱工具网源码优化版

应用介绍 本文来自:分享一个我爱工具网源码优化版 - 源码1688 前几天在网上看到了一个不错的工具网源码,但是源码存在一些问题,遂进行了修改优化。 主要修改内容有: 1、后台改为账号密码登录,上传即用,不…

算法分析-面试1-字符串

文章目录 前言一、分类:看看就行了二、字符串API:创建和初始化:查询操作:比较操作:修改操作:截取操作:分割操作:格式化操作:连接操作(Java 8 及以后&#xff…

pclpy KD-Tree半径最近邻搜索

pclpy 半径最近邻搜索 一、算法原理1.KD-Tree 介绍2.原理 二、代码三、结果1.原点云2.半径最近邻搜索的点云 四、相关数据 一、算法原理 1.KD-Tree 介绍 kd 树或 k 维树是计算机科学中使用的一种数据结构,用于在具有 k 维的空间中组织一定数量的点。它是一个二叉搜…

Windows下VTK 源码编译(For Qt PCL)

虽然我们在windows下安装PCL的时候就已经安装了VTK,由于跟着PCL安装的VTK是没有和QT联合编译的,所以在使用PCL和QT做点云可视化界面的时候是无法使用QT的插件QVTKWidget。 VTK 源码下载 Tags VTK / VTK GitLab 我这里的环境是Win10 Visual Studio&…

Qt 设置隐式加载dll路径

在c++中DLL的加载方式有两种,显式加载和隐式加载。 隐式加载 在程序从开始运行时,就会按照系统中一定的搜索路径,寻找动态库,找到就自动加载它,才能成功运行程序,这些步骤,是系统自动完成的。 显示加载 我们对动态库的调用,是在代码中直接使用LoadLibrary,或其他加载函…

ContainerHelpers之二分查找算法详解

目录 前言一、JAVA移位运算符1.1 >> 带符号右移位运算符1.2 >>> 无符号右移位运算符1.3 << 左移位运算符1.4 Java 中没有 <<<1.5 ~取反操作 二、ContainerHelpers二分查找算法总结 前言 安卓SparseArray中多次用到了ContainerHelpers的binarySe…

Android java中包的使用

一.包的使用 为了更好的实现项目中类的管理&#xff0c;提供包的概念。 package语句作为Java源文件的第一条语句&#xff0c;指明该文件中定义的类所在的包。(若缺省该语句&#xff0c;则指定为无名包)。 它的格式为&#xff1a;package 顶层包名.子包名 ; 二.java中主要的包…

Leetcode3039. 进行操作使字符串为空

Every day a Leetcode 题目来源&#xff1a;3039. 进行操作使字符串为空 解法1&#xff1a;哈希 排序 操作的定义&#xff1a;每次操作依次遍历 ‘a’ 到 ‘z’&#xff0c;如果当前字符出现在 s 中&#xff0c;那么删除出现位置最早的该字符&#xff08;如果存在的话&…

【ArcGIS】利用DEM进行水文分析:流向/流量等

利用DEM进行水文分析 ArcGIS实例参考 水文分析通过建立地表水文模型&#xff0c;研究与地表水流相关的各种自然现象&#xff0c;在城市和区域规划、农业及森林、交通道路等许多领域具有广泛的应用。 ArcGIS实例 某流域30m分辨率DEM如下&#xff1a; &#xff08;1&#xff09…

机器学习模型的过拟合与欠拟合

机器学习模型的训练过程中&#xff0c;可能会出现3种情况&#xff1a;模型欠拟合、模型正常拟合与模型过拟合。其中模型欠拟合与模型过拟合都是不好的情况。下面将会从不同的角度介绍如何判断模型属于哪种拟合情况。 &#xff08;1&#xff09;欠拟合与过拟合表现方式 欠拟合…

适配器模式:转换接口,无缝对接不同系统

文章目录 **一、技术背景与应用场景****为什么使用适配器模式&#xff1f;****典型应用场景包括但不限于&#xff1a;** **二、适配器模式定义与结构****三、使用步骤举例****四、优缺点分析****总结** 一、技术背景与应用场景 适配器模式在软件设计中扮演着桥梁角色&#xff…

十一、Qt数据库操作

一、Sql介绍 Qt Sql模块包含多个类&#xff0c;实现数据库的连接&#xff0c;Sql语句的执行&#xff0c;数据获取与界面显示&#xff0c;数据与界面直接使用Model/View结构。1、使用Sql模块 &#xff08;1&#xff09;工程加入 QT sql&#xff08;2&#xff09;添加头文件 …

【SRE系列】--部署gitlab

1、部署gitlab 1.1下载gitlab安装包并安装 下载地址&#xff1a;https://mirrors.tuna.tsinghua.edu.cn/gitlab-ce/ubuntu/pool/ rootk8s-gitlab:~# wget https://mirrors.tuna.tsinghua.edu.cn/gitlab-ce/ubuntu/pool/bionic/main/g/gitlab-ce/gitlab-ce_16.1.4-ce.0_amd64.d…

抖音视频提取软件使用功能|抖音视频下载工具

我们的抖音视频提取软件是一款功能强大、易于操作的工具&#xff0c;旨在解决用户在获取抖音视频时需要逐个复制链接、下载的繁琐问题。我们的软件支持通过关键词搜索和分享链接两种方式获取抖音视频&#xff0c;方便用户快速找到自己感兴趣的内容。 主要功能模块&#xff1a;…

Linux之JAVA环境配置jdkTomcatMySQL

目录 一. 安装jdk 1.1 查询是否有jdk 1.2 解压 1.3 配置环境变量 二. 安装Tomcat&#xff08;开机自启动&#xff09; 2.1 解压 2.2 启动tomcat 2.3 防火墙设置 2.4 创建启动脚本&#xff08;设置自启动&#xff0c;服务器开启即启动&#xff09; 三. MySQL安装&#xff08;…

【前端素材】推荐优质后台管理系统Sneat平台模板(附源码)

一、需求分析 后台管理系统是一种用于管理网站、应用程序或系统的工具&#xff0c;它通常作为一个独立的后台界面存在&#xff0c;供管理员或特定用户使用。下面详细分析后台管理系统的定义和功能&#xff1a; 1. 定义 后台管理系统是一个用于管理和控制网站、应用程序或系统…

Guitar Pro8.2吉他软件2024中文版功能特点介绍

Guitar Pro 8.2是一款功能强大的吉他乐谱软件&#xff0c;专为吉他手、音乐制作人和音乐爱好者设计。它提供了丰富的功能&#xff0c;帮助用户轻松创建、编辑、打印和分享吉他乐谱。以下是Guitar Pro 8.2的主要功能特点&#xff1a; Guitar Pro 2024 win-安装包下载如下&#x…

go interface{} 和string的转换问题

1.遇到的问题 问题来源于,我sql模版拼接遇到的问题。 首先&#xff0c;这样是没有问题的。 var qhx interface{} "qhx"s : qhx.(string)fmt.Println(s) 但是当我在这段代码里用:1.类型断言 var sqlStr "select * from tx_user where username %s" join…