HOME> 世界杯北京> 大模型应用开发——问答系统回答准确性评估的三类方法

大模型应用开发——问答系统回答准确性评估的三类方法

2025-05-25 03:44:53     世界杯北京    

在开发了基于文档的问答系统之后,需要评估系统对问题回答的准确性,将系统的回答与正确答案进行比对并给出评分。

我们实践了以下三类方法,最终对比发现,在评估系统回答的准确性时,用大模型来评估最有效。本文旨在给出大模型的prompt供参考,可以根据自己的需求调整。

另两类方法仅作简单介绍。

方案一:用大模型评估系统回答与正确答案的相似度。

大模型prompt

prompt1 = '''

你是一个天文学领域专家。

你将收到一个问题、正确答案和模型回答。

你的任务是通过将模型回答与正确答案进行比较,判断模型回答的准确程度,给出准确程度accuracy。

其中,accuracy的范围为0-1,模型回答越接近标准答案分数越高。

评价标准和步骤如下:

-1.详细阅读提交的问题。

-2.思考这个问题,并阅读给定的正确答案,确保理解了问题的内容以及正确答案的含义。

-3.阅读模型的回答。

-4.比较模型的回答与正确答案,理解模型回答中的信息和正确答案的相似程度以及不同之处。

-5.评价模型的回答,给出accuracy。如果模型的回答完全正确,无误差,给1分。如果模型的回答部分正确,但有一些信息缺失,可以给予中等的分数。如果模型的回答部分正确,部分错误,可以给定偏低的分数。如果模型的回答完全错误,或者与给定的正确答案无关,可以给0分。

-6.根据我的示例对待打分的问答对打分。

-7.不要给出思考过程,直接给出结果accuracy。

我的示例如下:

问题:空间站多功能光学设施的主要任务是什么?

正确答案:空间站多功能光学设施的主要任务是大规模天文巡天。空间站多功能光学设施是我国载人航天工程规划建设的大型空间天文望远镜,口径2米,兼具大视场和高像质的优异性能,并具备在轨维护升级的能力。其观测模式包括位置切换观测模式和OTF观测模式,其中OTF观测模式主要用于大面积天区的高效成图观测。

模型回答:空间站多功能光学设施的主要任务是大规模天文巡天。

accuracy:0.6

待打分的问答对:

问题:

{{question}}

正确答案:

{{correct_answer}}

模型回答:

{{model_answer}}

模型结果:

-accuracy:

'''

后续无论是用文心一言还是chatgpt都可以用这个prompt来实现,注意文心一言的系统指令是写在字段“system”里的。

以下给出用文心一言来判断的参考代码:

# 设置百度文心一言的API密钥和端点

API_KEY = "your_api_key"

SECRET_KEY = "your_secret_key"

import requests

import requests

import json

import time

# 配置文心一言的密钥和端点

def get_access_token():

"""

使用 AK,SK 生成鉴权签名(Access Token)

:return: access_token,或是None(如果错误)

"""

url = "https://aip.baidubce.com/oauth/2.0/token"

params = {"grant_type": "client_credentials", "client_id": API_KEY, "client_secret": SECRET_KEY}

return str(requests.post(url, params=params).json().get("access_token"))

# 大模型评估回答准确率

def evaluate_accuracy(question, correct_answer, model_answer):

url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions?access_token=" + get_access_token()

content= "判断模型回答的准确程度"

prompt = prompt1.replace("{{question}}", question).replace("{{correct_answer}}", correct_answer).replace("{{model_answer}}", model_answer)

payload = json.dumps({

"messages": [

{

"role": "user",

"content": content

}

],

"temperature": 0.95,

"top_p": 0.8,

"system":prompt

})

headers = {

'Content-Type': 'application/json'

}

start_time = time.time()

response = requests.request("POST", url, headers=headers, data=payload)

x = json.loads(response.text)

print("耗时", time.time() - start_time)

print(question)

print(x)

if response.status_code == 200:

return x['result']

else:

print(f"Error: {response.status_code}")

print(response.content)

return None

# 如果想要将大模型评估的结果提取出具体的准确率分数,可以用下面这个函数,将上面函数的x['result']作为本函数的入参

import re

def extract_accuracy(row):

try:

match = re.search(r'accuracy[\s::]+([0-9.]+)', row)

if match:

return float(match.group(1))

else:

return np.nan

except Exception as e:

return np.nan

方案二:Semantic Textual Similarity (STS)语义相似度检测

可以自行搜索原理,参考代码如下:

from sentence_transformers import SentenceTransformer, util

# 初始化模型

model = SentenceTransformer('paraphrase-MiniLM-L6-v2')

def compute_sts(sentence1, sentence2):

# 计算句子的嵌入

embedding1 = model.encode(sentence1, convert_to_tensor=True)

embedding2 = model.encode(sentence2, convert_to_tensor=True)

# 计算余弦相似度

similarity = util.pytorch_cos_sim(embedding1, embedding2).item()

return similarity

# 示例使用

sentence1 = "量数据缺乏或完备度、准确度不够的分子光谱,在实验室进行测定。"

sentence2 = "在实验室进行测定。"

sts_score = compute_sts(sentence1, sentence2)

print(f"STS Score: {sts_score}")

方案三:BLEU/ROUGE/Exact Match/BERTScore等基于字符串匹配的方法

这里给出BLEU、ROUGE、bert_score的参考代码:

from sklearn.metrics import accuracy_score

from nltk.translate.bleu_score import sentence_bleu

from rouge import Rouge

from bert_score import score as bert_score

import numpy as np

# 定义方法

def evaluate_responses(predictions, references):

# 初始化评估指标

bleu_scores = []

rouge = Rouge()

rouge_scores = []

exact_matches = []

for pred, ref in zip(predictions, references):

# BLEU Score

bleu_score_value = sentence_bleu([ref.split()], pred.split())

bleu_scores.append(bleu_score_value)

# ROUGE Score

rouge_score_value = rouge.get_scores(pred, ref)[0]

rouge_scores.append(rouge_score_value)

# Exact Match

exact_match = 1 if pred == ref else 0

exact_matches.append(exact_match)

# BERTScore

P, R, F1 = bert_score(predictions, references, lang="zh", verbose=True)

bert_scores = F1.tolist()

# 计算平均得分

avg_bleu = np.mean(bleu_scores)

avg_rouge = {key: np.mean([score[key]['f'] for score in rouge_scores]) for key in rouge_scores[0]}

avg_exact_match = np.mean(exact_matches)

avg_bert_score = np.mean(bert_scores)

results = {

"BLEU": avg_bleu,

"ROUGE": avg_rouge,

"Exact Match": avg_exact_match,

"BERTScore": avg_bert_score

}

return results

# 示例使用

predictions = ["这是系统生成的答案", "另一个系统答案"]

references = ["这是标准答案", "另一个标准答案"]

results = evaluate_responses(predictions, references)

print(results)