《Advanced RAG》-03-使用 RAGAs + LlamaIndex 进行 RAG 评估

news2024/10/1 19:23:44

摘要

文章首先介绍了 RAG 评估的三个主要部分:输入查询、检索上下文和 LLM 生成的响应。

提到了 RAGAs 提出的 RAG 评估指标,包括 Faithfulness、Answer Relevance 和 Context Relevance,以及 RAGAs 网站提供的两个额外指标:Context Precision 和 Context Recall。详细解释了每个指标的计算方法,并提供了一些示例。

最后,它介绍了使用 RAGAs 和 LlamaIndex 进行 RAG 评估的主要过程。

文章观点

RAG 评估是一个复杂的过程,需要多种指标来评估 RAG 的有效性。RAGAs 和 LlamaIndex 提供了一种有效的方法来进行 RAG 评估,可以帮助开发人员改进 RAG 应用程序的性能。

如果为实际业务系统开发了一个检索增强生成(RAG)应用程序,有效性会很重要。换句话说,需要评估 RAG 的性能如何。

如果发现现有的 RAG 不够有效,可能需要验证 RAG 改进方法的有效性。同时也需要进行评估,看看这些改进方法是否有效。

在本文中,首先介绍 论文 RAGAs(Retrieval Augmented Generation Assessment)提出的 RAG 评估指标,这是一个用于评估 RAG 管道的框架。然后,将继续解释如何使用 RAGAs + LlamaIndex 实现整个评估流程。

RAG 评估指标

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

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

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

论文 RAGAs(Retrieval Augmented Generation Assessment)总共提到了 3 个指标:这些指标无需访问人工标注的数据集或参考答案。

此外,RAGAs 网站还介绍了另外两个指标:上下文精确度和上下文召回率。

忠实性|稳定性(Faithfulness/Groundedness)

忠实性:是指确保答案以给定的上下文为基础。

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

如果得分较低,则表明LLM的回答与检索到的知识不符,提供幻觉答案的可能性就会增加。例如
在这里插入图片描述
为了估计忠实性,我们首先使用 LLM 提取一组语句 S(a(q))。具体方法如下:

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 会判断每条语句 si是否都能从 c(q)中推断出来。这一验证步骤通过以下提示进行:

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| 代表语句总数。

答案相关性(Answer Relevance)

该指标衡量生成的答案与查询之间的相关性。分数越高,相关性越好。例如

在这里插入图片描述

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

Generate a question for the given answer.
answer: [answer]

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

对于每个 qi,计算与原始问题 q 的相似度 sim(q,qi),这相当于嵌入之间的余弦相似度。问题 q 的答案相关性得分 AR 计算如下:

在这里插入图片描述

上下文相关性(Context Relevance)

这是一个衡量检索质量的指标,主要评估检索到的上下文对查询的支持程度。得分低表示检索到大量无关内容,这可能会影响 LLM 生成的最终答案。例如

在这里插入图片描述

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

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 中,相关性是通过以下公式在句子层面计算的:

在这里插入图片描述

上下文召回率(Context Recall)

该指标衡量的是检索上下文与标记的答案之间的一致性水平。

它使用基本事实和检索到的上下文进行计算,数值越高,表示性能越好。例如

在这里插入图片描述

在实施时,需要提供基础实况数据。计算公式如下

在这里插入图片描述

上下文准确度(Context Precision)

这一指标相对复杂,用于衡量检索到的包含真实情况的所有相关上下文是否都排在前列。得分越高,表示精确度越高。

该指标的计算公式如下:

在这里插入图片描述

上下文精度的优点是能够感知排名效果。但它的缺点是,如果相关的召回次数很少,但排名都很靠前,得分也会很高。因此,有必要结合其他几个指标来考虑整体效果。

使用 RAGAs + LlamaIndex 进行 RAG 评估

主要流程如图 6 所示:

在这里插入图片描述

环境配置

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

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

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

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

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: An Open Source Small Language Model”。

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

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

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

默认情况下,LlamaIndex 使用 OpenAI 模型,但可以使用 ServiceContext 轻松配置 LLM 和嵌入模型。

构建评估数据集

由于有些指标需要人工标注数据集,我自己编写了一些问题及其相应的答案。

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 评估

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 版中找到任何有用的方法。

最终代码

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 数据框架可能无法完全显示。如图 6 所示,您可以将其导出为 CSV 文件来查看。

在这里插入图片描述

从图 6 中可以明显看出:

  • 第四个问题 “Tell me about starcoderdata dataset” 的所有答案都是 0。这是因为 LLM 无法提供答案。
  • 第二个和第三个问题的上下文精确度为 0,这表明检索到的上下文中相关的上下文没有排在最前面。
  • 第二个问题的上下文召回率为 0,表明检索到的上下文与注释答案不匹配。

这些问题的答案相关性得分很高,表明答案与问题之间有很强的相关性。

此外,忠实度得分也不低,这表明答案主要是根据上下文推导或总结出来的,因此可以断定这些答案不是由 LLM 产生的幻觉。

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

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

结论

总的来说,RAGAs 提供了全面的 RAG 评估指标,并且调用方便。

目前缺乏 RAG 评估框架,RAGAs 提供了一个有效的工具。

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

本文为翻译,原文地址:https://medium.com/ai-in-plain-english/advanced-rag-03-using-ragas-llamaindex-for-rag-evaluation-84756b82dca7

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

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

相关文章

Jenkins未授权访问漏洞 *

漏洞复现 步骤一:使用以下fofa语法进行产品搜索.... port"8080" && app"JENKINS" && title"Dashboard [Jenkins]" 步骤二:在打开的URL中...点击Manage Jenkins --> Scritp Console在执行以下命令..…

JS使用 navigator.clipboard 操作剪切板

注意:需要在安全域下才能够使用,比如:https 协议的地址、127.0.0.1、localhost safari浏览器需要打开配置,在地址栏输入 about:config,搜索 clipboard,将 asyncClipboard 由 false 改为 true,然…

8.3,8.4总结

1.改进渲染 // 加载头像图像InputStream inputStream new ByteArrayInputStream(message.getFileBytes());Image image new Image(inputStream); // 第二个参数表示是否缓存图片,根据需要设置imageView.setImage(image);// 设置头像视图大小imageView.setFitWidth…

安装eclipse时候 打开eclipse出现一连串英文

问题描述:打开eclipse失败,提示错误Version 1.8.xx of the JVM is not suitable for this product Version:11 or greater is required 本地已经有1.8.XX 的jdk,但因为新安装的eclipse需要JVM更高的版本。 原因:jdk版本太低 解…

基于随机森林、XGBoost、lightGBM的大气污染预测可视化系统【前后端交互】

文章目录 有需要本项目的代码或文档以及全部资源,或者部署调试可以私信博主数据介绍系统界面展示系统登陆展示系统主界面可视化展示机器学习模型预测展示框架界面功能每文一语 有需要本项目的代码或文档以及全部资源,或者部署调试可以私信博主 数据介绍…

【C语言】C语言期末突击/考研--结构体与C++引用

一、结构体--结构体对齐--结构体数组 1.1.结构体的定义、初始化、结构体数组 有时候需要将不同类型的数据组合为一一个整体,以便于引用。 例如,一名学生有学号、姓 名、性别、年龄、地址等属性,如果针对学生的学号、姓名、年龄等都单独定义一…

代码坏味道有24种?我看未必

微信公众号:牛奶 Yoka 的小屋 有任何问题。欢迎来撩~ 最近更新:2024/08/03 [大家好,我是牛奶。] 我在上一篇文章打开IDEA,程序员思考的永远只有两件事!中,通过代码命名、重复代码、合格方法三个章节&#…

PXE实验

实验前准备 关闭VMware的dhcp 点击 编辑 点击 虚拟网络编辑器 选择 NAT模式 将dhcp取消勾选 准备两台虚拟机 一台试验机,(网络环境正常并且有图形化的界面的rhel7) 一台测试机 init 5 --------------> 开启图形化界面 如…

《C/C++实战进阶》介绍

🚀 前言 本文是《C/C实战进阶》专栏的说明贴(点击链接,跳转到专栏主页,欢迎订阅,持续更新…)。 专栏介绍:以多年的开发实战为基础,总结并讲解一些的C/C基础与项目实战进阶内容&…

AI用Alice_split_toolset切割音频的采样率

AI用Alice_split_toolset切割音频的采样率 目录 AI用Alice_split_toolset切割音频的采样率 一、Sample rate采样率的概念 二、Alice_split_toolset切割音频的参数 2.1、字符串参数--input_folder输入文件夹路径 2.2、字符串参数--output_folder输出文件夹路径 2.3、字符串…

第一次作业,sql注入总结

sqli-labs靶场中演示: less1: 注入点为: $sql"SELECT * FROM users WHERE id$id LIMIT 0,1"; get输入一个id,可以逃逸出单引号来实现sql注入。 正常的输入为,输出数据库中查询的内容。 http://127.0.0…

如何将PyCharm 中使用 PDM 管理的 Django 项目迁移到 VS Code 并确保一切正常工作?

嗨,我是兰若姐姐,相信很多小伙伴都遇到过这种情况,使用pycharm用习惯了,想换个编辑器,比如换成vscode,今天就告诉大家,如果轻松切换到vscode 步骤 1:在 VS Code 中打开项目 打开 V…

并行状态的广播事件

平行状态的广播事件 此示例显示了并行状态下事件广播操作的行为。 最初,图表处于休眠状态。并行子状态A.A1.A1a和A.A2.A2a处于活动状态。事件E_one发生并唤醒图表,图表从根向下通过层次结构处理事件: 1 图表根会检查根级别是否存在E_one导致…

Docker简介 MacM1安装Docker

文章目录 1 Docker简介2 Docker VS 虚拟机1 Docker优势2 Docker用途 3 MacM1 下载安装Docker1 配置环境变量 4 配置Docker2 设置Docker资源3 设置Docker镜像 参考 1 Docker简介 Docker主要解决了软件开发和运行配置的问题,但是由于其功能的强大,也被应用…

跨境电商下载工具天猫主图sku图等图片信息

优美的图片是电商卖家吸引顾客、展示商品魅力的关键。高质量的图片能够提升产品吸引力,增强用户信任感,促进购买决策,从而直接影响销量和店铺形象。在视觉营销的时代,优秀的商品图片更是流量转化的利器。 使用图快下载器&#xf…

多租户系统数据隔离方案

目录 前言 数据行 数据表 基于业务场景 基于数据量 数据库 数据源表 动态数据源 前言 多租户系统是一种将多个客户的数据和应用程序分开的系统,每个客户被视为一个独立的租户,互不干扰。实现多租户系统的关键之一是确保数据的隔离。 数据隔离的…

Windows 添加自定义服务实现开机(用户登录之前)自动运行 Python 脚本

实现效果 使用 Python 编写的一个脚本, 希望在 Windows 系统启动时, 用户登录之前就自动运行. 准备工作 首先确保 Python 脚本可以手动正常运行, 演示起见, 编写下面的一个简单的脚本用于在 C 盘根目录中生成一个包含脚本运行时间戳的文本文件. Python 脚本存放在 C:\Python…

RISC-V (五)上下文切换和协作式多任务

任务(task) 所谓的任务就是寄存器的当前值。 -smp后面的数字指的是hart的个数,qemu模拟器最大可以有8个核,此文围绕一个核来讲。 QEMU qemu-system-riscv32 QFLAG -nographic -smp 1 -machine virt -bios none 协作式多任务 …

绘唐科技,绘唐3高级推理创作

绘唐科技,绘唐3高级推理创作绘唐3https://qvfbz6lhqnd.feishu.cn/wiki/D3YLwmIzmivZ7BkDij6coVcbn7W 《绘唐3:高级推理创作》 第一章:谋杀案的启示 在古代绘唐王朝的京都,发生了一起离奇的谋杀案。一位名叫李红的官员&#xff0c…

[Day 44] 區塊鏈與人工智能的聯動應用:理論、技術與實踐

生成对抗网络(Generative Adversarial Networks,GANs)是一种由Ian Goodfellow等人在2014年提出的深度学习模型,广泛用于图像生成、图像超分辨率、图像修复等领域。GAN由一个生成器(Generator)和一个判别器&…