使 LLM 评估器与人类判断对齐
本教程是关于如何将 Vertex AI 模型与 Ragas 结合使用的三部分系列教程之一。建议您先阅读入门:将 Ragas 与 Vertex AI 结合使用,但即使没有阅读,您也可以轻松跟上本教程。您可以使用此链接导航到模型比较教程。
概述
在本教程中,您将学习如何使用 Ragas 训练和对齐您自己的基于 LLM 的自定义指标。虽然基于 LLM 的评估器为 AI 应用评分提供了一种强大的方法,但由于风格、上下文或细微差别的差异,它们有时会产生与人类期望不符的判断。通过遵循本指南,您将优化您的指标,使其更准确地反映人类的判断。
在本教程中,您将:
- 使用 Ragas 定义一个基于模型的指标。
- 从 HHH 数据集的“helpful”子集构建一个 EvaluationDataset。
- 运行初步评估,以对该指标的性能进行基准测试。
- 审查并标注 15-20 个评估示例。
- 使用您的标注数据训练该指标。
- 重新评估该指标,以观察其与人类判断对齐度的改善情况。
入门指南
安装依赖项
重启运行时
要在此 Jupyter 运行时中使用新安装的包,您必须重新启动运行时。您可以通过运行下面的单元格来完成此操作,它会重新启动当前内核。
重启可能需要一分钟或更长时间。重启后,继续下一步。
验证您的笔记本环境(仅限 Colab)
如果您在 Google Colab 上运行此笔记本,请运行下面的单元格来验证您的环境。
设置 Google Cloud 项目信息并初始化 Vertex AI SDK
PROJECT_ID = "[your-project-id]" # @param {type:"string"}
LOCATION = "us-central1" # @param {type:"string"}
if not PROJECT_ID or PROJECT_ID == "[your-project-id]":
raise ValueError("Please set your PROJECT_ID")
import vertexai
vertexai.init(project=PROJECT_ID, location=LOCATION)
设置评估指标
基于 LLM 的指标潜力巨大,但与人类评估者相比,有时可能会误判响应。为了弥合这一差距,我们使用反馈循环将基于模型的指标与人类判断对齐。
定义 evaluator_llm
导入所需的包装器,并定义您的评估器 LLM 和嵌入器。
from ragas.llms import LangchainLLMWrapper
from ragas.embeddings import LangchainEmbeddingsWrapper
from langchain_google_vertexai import VertexAI, VertexAIEmbeddings
evaluator_llm = LangchainLLMWrapper(VertexAI(model_name="gemini-2.0-flash-001"))
evaluator_embeddings = LangchainEmbeddingsWrapper(VertexAIEmbeddings(model_name="text-embedding-004"))
Ragas 指标
Ragas 提供了各种基于模型的指标,可以进行微调以与人类评估者对齐。为作演示,我们将使用 Aspect Critic 指标——一种用户定义的二元指标。有关更多详细信息,请参阅 Aspect Critic 文档。
from ragas.metrics import AspectCritic
helpfulness_critic = AspectCritic(
name="helpfulness",
definition="Evaluate how helpful the assistant's response is to the user's query.",
llm=evaluator_llm
)
您可以通过运行以下命令预览将(在对齐前)传递给 LLM 的提示:
输出Evaluate the Input based on the criterial defined. Use only 'Yes' (1) and 'No' (0) as verdict.
Criteria Definition: Evaluate how helpful the assistant's response is to the user's query.
定义对齐分数
由于我们使用的是二元指标,我们将使用 F1 分数来衡量对齐度。但是,根据您正在对齐的指标,您可以相应地修改此函数以使用其他方法来衡量对齐度。
from typing import List
from sklearn.metrics import f1_score
def alignment_score(human_score: List[float], llm_score: List[float]) -> float:
"""
Computes the alignment between human-annotated binary scores and LLM-generated binary scores
using the F1-score metric.
Args:
human_score (List[int]): Binary labels from human evaluation (0 or 1).
llm_score (List[int]): Binary labels from LLM predictions (0 or 1).
Returns:
float: The F1-score measuring alignment.
"""
return f1_score(human_score, llm_score)
准备您的数据集
process_hhh_dataset 函数准备来自 HHH 数据集的数据,用于训练和对齐 LLM 评估器。每个示例被交替分配 0 分和 1 分(1 代表有帮助,0 代表无帮助),以表明哪个响应更受青睐。
import numpy as np
from datasets import load_dataset
from ragas import EvaluationDataset
def process_hhh_dataset(split: str = "helpful", total_count: int = 50):
dataset = load_dataset("HuggingFaceH4/hhh_alignment",split, split=f"test[:{total_count}]")
data = []
expert_scores = []
for idx, entry in enumerate(dataset):
# Extract input and target details
user_input = entry['input']
choices = entry['targets']['choices']
labels = entry['targets']['labels']
# Choose target based on whether the index is even or odd
if idx % 2 == 0:
target_label = 1
score = 1
else:
target_label = 0
score = 0
label_index = labels.index(target_label)
response = choices[label_index]
data.append({
'user_input': user_input,
'response': response,
})
expert_scores.append(score)
return EvaluationDataset.from_list(data), expert_scores
eval_dataset, expert_scores = process_hhh_dataset()
运行评估
在定义了评估数据集和有帮助性指标后,您现在可以运行评估:
这次初步运行突显了基于 LLM 的评估器中存在的不对齐程度,后续的训练将解决这个问题。
接下来,将指标的性能与专家分数进行基准比较:
human_score = expert_scores
llm_score = results.to_pandas()["helpfulness"].values
initial_score = alignment_score(human_score, llm_score)
initial_score
审查与标注
既然您已获得评估结果,现在是时候对它们进行审查和标注了。正如博客 《使作为裁判的 LLM 与人类评估者对齐》中所讨论的,收集详细反馈对于弥合基于 LLM 的评估和人类评估之间的差距至关重要。请至少标注 15-20 个示例,以捕捉指标可能不对齐的各种场景。
这是上述示例的一个样本标注。您可以下载并使用它。
训练与对齐
下一步是使用已标注的示例来训练您的指标。此训练过程采用了一种无梯度的提示优化方法,该方法会根据标注的反馈调整指令和少样本示例。
from ragas.config import InstructionConfig, DemonstrationConfig
demo_config = DemonstrationConfig(embedding=evaluator_embeddings)
inst_config = InstructionConfig(llm=evaluator_llm)
helpfulness_critic.train(
path="annotated_data.json",
instruction_config=inst_config,
demonstration_config=demo_config,
)
Overall Progress: 100%|██████████| 170/170 [00:00<?, ?it/s]
Few-shot examples [single_turn_aspect_critic_prompt]: 100%|██████████| 16/16 [00:00<?, ?it/s]
训练后,审查已为该指标优化的更新后指令:
输出You are provided with a user input and an assistant/model response. Your task is to evaluate the quality of the response based on how well it addresses the user input, considering all requests and constraints. Assign a score/verdict of 1 if the response is helpful, appropriate, and effective, and 0 if it is not. A good response should be accurate, complete, relevant, and provide a tangible improvement or solution, without omitting key information. Provide a brief explanation for your score/verdict.
重新评估
现在您的指标已与人类反馈对齐,请在您的数据集上重新运行评估。此步骤使您能够对改进进行基准测试,并量化对齐过程在多大程度上提高了指标的可靠性。
from ragas.llms import LangchainLLMWrapper
from ragas.embeddings import LangchainEmbeddingsWrapper
from langchain_google_vertexai import VertexAI, VertexAIEmbeddings
evaluator_llm = LangchainLLMWrapper(VertexAI(model_name="gemini-pro"))
evaluator_embeddings = LangchainEmbeddingsWrapper(VertexAIEmbeddings(model_name="text-embedding-004"))
将更新后的结果与专家分数进行基准比较:
human_score = expert_scores
llm_score = results2.to_pandas()["helpfulness"].values
new_score = alignment_score(human_score, llm_score)
new_score
查看本系列的其他教程
- 将 Ragas 与 Vertex AI 结合使用:学习如何将 Vertex AI 模型与 Ragas 结合使用,以评估您的 LLM 工作流。
- 模型比较:使用 Ragas 指标,比较 VertexAI 提供的模型在基于 RAG 的问答任务上的表现。