llm-evaluation-zh
Installation
Review the source and dependencies with a prompt. A package is available to download.
Install with an AI assistant
Copy the prompt so your assistant can review the pinned revision and dependencies first.
View promptHide prompt
Check whether SkillPI Skill Finder is installed for your current agent. If it is missing, install and enable it using the official instructions at https://github.com/Findskills/skillpi. Then use Skill Finder to locate and install "llm-evaluation-zh" from this exact SkillPI detail page: https://skillpi.com/skills/deepskill-d975c150e21d1ea90c71ab43043c5a3704d439d3f9c066329c966f4c5edcd62a. Verify the upstream source and version against https://skillhub.cn/skills/org-02qudk26/llm-evaluation-zh before installing. If they do not match, stop and report the mismatch. Report the installed path and source version.
Source and setup
skillhub.cn
Setup guidance pending
See the original source for supported tools, dependencies, and permissions.
Installation test pending
llm-evaluation-zh: Provides a comprehensive evaluation strategy for LLM applications, combining automated metrics, human feedback, and benchmark testing. Suitable for testing LLM performance, measuring AI application quality, or establishing an evaluation framework.
Introduction source: third_party · org-02qudk26 · 1.0.0 Reference
SkillPi interpretation
- Tasks
- Translation pending; see source documentation.
- Audience
- Translation pending; see source documentation.
- Testing
- Not tested
Browse files
Frontmatter
name: llm-evaluation
displayName: LLM 评估
description: 使用自动化指标、人工反馈和基准测试为 LLM 应用实现全面的评估策略。适用于测试 LLM 性能、衡量 AI 应用质量或建立评估框架。
slug: hub-llm-evaluationLLM 评估
掌握 LLM 应用的全面评估策略,从自动化指标到人工评估和 A/B 测试。
不适合使用此技能的场景
- 任务与 LLM 评估无关
- 需要超出此范围的领域或工具
使用说明
- 明确目标、约束条件和所需输入
- 应用相关的最佳实践并验证结果
- 提供可操作的步骤和验证
- 如需详细示例,打开
resources/implementation-playbook.md
使用此技能的场景
- 系统性地衡量 LLM 应用性能
- 比较不同模型或提示词
- 在部署前检测性能回归
- 验证提示词变更的改进效果
- 建立对生产系统的信心
- 建立基线并跟踪长期进展
- 调试意外的模型行为
核心评估类型
1. 自动化指标
快速、可重复、可扩展的基于计算分数的评估。
文本生成:
- BLEU:N-gram 重叠度(翻译)
- ROUGE:基于召回率的评估(摘要)
- METEOR:语义相似度
- BERTScore:基于嵌入的相似度
- Perplexity:语言模型置信度
分类任务:
- Accuracy:正确率
- Precision/Recall/F1:类别特定性能
- Confusion Matrix:错误模式分析
- AUC-ROC:排序质量
检索(RAG):
- MRR:平均倒数排名
- NDCG:归一化折损累计增益
- Precision@K:前 K 个中的相关项
- Recall@K:前 K 个中的覆盖率
2. 人工评估
对难以自动化的质量维度进行人工评估。
评估维度:
- 准确性:事实的正确性
- 连贯性:逻辑流畅度
- 相关性:回答了问题
- 流畅度:自然语言质量
- 安全性:无有害内容
- 有用性:对用户有帮助
3. LLM 作为评委
使用更强的 LLM 评估较弱模型的输出。
方法:
- 逐点评分:对单个响应进行评分
- 成对比较:比较两个响应
- 基于参考:与标准答案比较
- 无参考:无需标准答案进行评判
快速开始
from llm_eval import EvaluationSuite, Metric
# 定义评估套件
suite = EvaluationSuite([
Metric.accuracy(),
Metric.bleu(),
Metric.bertscore(),
Metric.custom(name="groundedness", fn=check_groundedness)
])
# 准备测试用例
test_cases = [
{
"input": "法国的首都是什么?",
"expected": "巴黎",
"context": "法国是一个欧洲国家。巴黎是其首都。"
},
# ... 更多测试用例
]
# 运行评估
results = suite.evaluate(
model=your_model,
test_cases=test_cases
)
print(f"总体准确率:{results.metrics['accuracy']}")
print(f"BLEU 分数:{results.metrics['bleu']}")
自动化指标实现
BLEU 分数
from nltk.translate.bleu_score import sentence_bleu, SmoothingFunction
def calculate_bleu(reference, hypothesis):
"""计算参考与假设之间的 BLEU 分数。"""
smoothie = SmoothingFunction().method4
return sentence_bleu(
[reference.split()],
hypothesis.split(),
smoothing_function=smoothie
)
# 使用示例
bleu = calculate_bleu(
reference="The cat sat on the mat",
hypothesis="A cat is sitting on the mat"
)
ROUGE 分数
from rouge_score import rouge_scorer
def calculate_rouge(reference, hypothesis):
"""计算 ROUGE 分数。"""
scorer = rouge_scorer.RougeScorer(['rouge1', 'rouge2', 'rougeL'], use_stemmer=True)
scores = scorer.score(reference, hypothesis)
return {
'rouge1': scores['rouge1'].fmeasure,
'rouge2': scores['rouge2'].fmeasure,
'rougeL': scores['rougeL'].fmeasure
}
BERTScore
from bert_score import score
def calculate_bertscore(references, hypotheses):
"""使用预训练 BERT 计算 BERTScore。"""
P, R, F1 = score(
hypotheses,
references,
lang='en',
model_type='microsoft/deberta-xlarge-mnli'
)
return {
'precision': P.mean().item(),
'recall': R.mean().item(),
'f1': F1.mean().item()
}
自定义指标
def calculate_groundedness(response, context):
"""检查响应是否基于提供的上下文。"""
# 使用 NLI 模型检查蕴含关系
from transformers import pipeline
nli = pipeline("text-classification", model="microsoft/deberta-large-mnli")
result = nli(f"{context} [SEP] {response}")[0]
# 返回响应被上下文蕴含的置信度
return result['score'] if result['label'] == 'ENTAILMENT' else 0.0
def calculate_toxicity(text):
"""衡量生成文本中的毒性。"""
from detoxify import Detoxify
results = Detoxify('original').predict(text)
return max(results.values()) # 返回最高毒性分数
def calculate_factuality(claim, knowledge_base):
"""验证事实性陈述与知识库的一致性。"""
# 实现取决于知识库
# 可使用检索 + NLI,或事实核查 API
pass
LLM 作为评委模式
单输出评估
def llm_judge_quality(response, question):
"""使用 GPT-5 评判响应质量。"""
prompt = f"""请按 1-10 分对以下响应进行评分:
1. 准确性(事实正确)
2. 有用性(回答问题)
3. 清晰度(编写良好且易懂)
问题:{question}
响应:{response}
以 JSON 格式提供评分:
{{
"accuracy": <1-10>,
"helpfulness": <1-10>,
"clarity": <1-10>,
"reasoning": "<简要解释>"
}}
"""
result = openai.ChatCompletion.create(
model="gpt-5",
messages=[{"role": "user", "content": prompt}],
temperature=0
)
return json.loads(result.choices[0].message.content)
成对比较
def compare_responses(question, response_a, response_b):
"""使用 LLM 评委比较两个响应。"""
prompt = f"""比较以下两个对问题的响应,判断哪一个更好。
问题:{question}
响应 A:{response_a}
响应 B:{response_b}
哪个响应更好以及为什么?考虑准确性、有用性和清晰度。
以 JSON 格式回答:
{{
"winner": "A" 或 "B" 或 "tie",
"reasoning": "<解释>",
"confidence": <1-10>
}}
"""
result = openai.ChatCompletion.create(
model="gpt-5",
messages=[{"role": "user", "content": prompt}],
temperature=0
)
return json.loads(result.choices[0].message.content)
人工评估框架
标注指南
class AnnotationTask:
"""人工标注任务的结构。"""
def __init__(self, response, question, context=None):
self.response = response
self.question = question
self.context = context
def get_annotation_form(self):
return {
"question": self.question,
"context": self.context,
"response": self.response,
"ratings": {
"accuracy": {
"scale": "1-5",
"description": "响应事实是否正确?"
},
"relevance": {
"scale": "1-5",
"description": "是否回答了问题?"
},
"coherence": {
"scale": "1-5",
"description": "逻辑是否一致?"
}
},
"issues": {
"factual_error": False,
"hallucination": False,
"off_topic": False,
"unsafe_content": False
},
"feedback": ""
}
评分者间一致性
from sklearn.metrics import cohen_kappa_score
def calculate_agreement(rater1_scores, rater2_scores):
"""计算评分者间一致性。"""
kappa = cohen_kappa_score(rater1_scores, rater2_scores)
interpretation = {
kappa < 0: "较差",
kappa < 0.2: "轻微",
kappa < 0.4: "一般",
kappa < 0.6: "中等",
kappa < 0.8: "显著",
kappa <= 1.0: "几乎完美"
}
return {
"kappa": kappa,
"interpretation": interpretation[True]
}
A/B 测试
统计测试框架
from scipy import stats
import numpy as np
class ABTest:
def __init__(self, variant_a_name="A", variant_b_name="B"):
self.variant_a = {"name": variant_a_name, "scores": []}
self.variant_b = {"name": variant_b_name, "scores": []}
def add_result(self, variant, score):
"""添加变体的评估结果。"""
if variant == "A":
self.variant_a["scores"].append(score)
else:
self.variant_b["scores"].append(score)
def analyze(self, alpha=0.05):
"""执行统计分析。"""
a_scores = self.variant_a["scores"]
b_scores = self.variant_b["scores"]
# T 检验
t_stat, p_value = stats.ttest_ind(a_scores, b_scores)
# 效应量(Cohen's d)
pooled_std = np.sqrt((np.std(a_scores)**2 + np.std(b_scores)**2) / 2)
cohens_d = (np.mean(b_scores) - np.mean(a_scores)) / pooled_std
return {
"variant_a_mean": np.mean(a_scores),
"variant_b_mean": np.mean(b_scores),
"difference": np.mean(b_scores) - np.mean(a_scores),
"relative_improvement": (np.mean(b_scores) - np.mean(a_scores)) / np.mean(a_scores),
"p_value": p_value,
"statistically_significant": p_value < alpha,
"cohens_d": cohens_d,
"effect_size": self.interpret_cohens_d(cohens_d),
"winner": "B" if np.mean(b_scores) > np.mean(a_scores) else "A"
}
@staticmethod
def interpret_cohens_d(d):
"""解释 Cohen's d 效应量。"""
abs_d = abs(d)
if abs_d < 0.2:
return "可忽略"
elif abs_d < 0.5:
return "小"
elif abs_d < 0.8:
return "中"
else:
return "大"
回归测试
回归检测
class RegressionDetector:
def __init__(self, baseline_results, threshold=0.05):
self.baseline = baseline_results
self.threshold = threshold
def check_for_regression(self, new_results):
"""检测新结果是否出现回归。"""
regressions = []
for metric in self.baseline.keys():
baseline_score = self.baseline[metric]
new_score = new_results.get(metric)
if new_score is None:
continue
# 计算相对变化
relative_change = (new_score - baseline_score) / baseline_score
# 如果显著下降则标记
if relative_change < -self.threshold:
regressions.append({
"metric": metric,
"baseline": baseline_score,
"current": new_score,
"change": relative_change
})
return {
"has_regression": len(regressions) > 0,
"regressions": regressions
}
基准测试
运行基准测试
class BenchmarkRunner:
def __init__(self, benchmark_dataset):
self.dataset = benchmark_dataset
def run_benchmark(self, model, metrics):
"""在基准数据集上运行模型并计算指标。"""
results = {metric.name: [] for metric in metrics}
for example in self.dataset:
# 生成预测
prediction = model.predict(example["input"])
# 计算每个指标
for metric in metrics:
score = metric.calculate(
prediction=prediction,
reference=example["reference"],
context=example.get("context")
)
results[metric.name].append(score)
# 汇总结果
return {
metric: {
"mean": np.mean(scores),
"std": np.std(scores),
"min": min(scores),
"max": max(scores)
}
for metric, scores in results.items()
}
资源
- references/metrics.md:全面指标指南
- references/human-evaluation.md:标注最佳实践
- references/benchmarking.md:标准基准测试
- references/a-b-testing.md:统计测试指南
- references/regression-testing.md:CI/CD 集成
- assets/evaluation-framework.py:完整评估框架
- assets/benchmark-dataset.jsonl:示例数据集
- scripts/evaluate-model.py:自动化评估运行器
最佳实践
- 多指标:使用多样化的指标获得全面视图
- 代表性数据:在真实世界、多样化的示例上进行测试
- 基线:始终与基线性能进行对比
- 统计严谨性:使用正确的统计检验进行比较
- 持续评估:集成到 CI/CD 流水线中
- 人工验证:自动化指标与人工判断相结合
- 错误分析:调查失败原因以了解弱点
- 版本控制:长期跟踪评估结果
常见陷阱
- 单一指标偏执:优化一个指标而牺牲其他指标
- 样本量过小:从过少的样本中得出结论
- 数据污染:在训练数据上进行测试
- 忽略方差:不考虑统计不确定性
- 指标不匹配:使用的指标与业务目标不一致
Current listing version
1.0.0
Safety and assessment details
Quality assessment
Out of 100 · Assessment report from SkillPi LAB.
Highlights
- 提供 LLM 评估的完整策略,涵盖自动化指标、人工评估、LLM 评委、A/B 测试、回归检测、基准测试等
- 直接解决用户测试 LLM 性能、衡量 AI 应用质量的核心痛点
- 适用于高频刚需场景,显著提升 AI 应用质量保障效率
Highlights
- description 明确说明适用于测试 LLM 性能、衡量 AI 应用质量或建立评估框架
- 触发词精准完整,边界清晰,覆盖多种变体
Highlights
- Phase/步骤清晰(核心评估类型、快速开始、实现、最佳实践等)
- 有出口条件,含端到端示例,frontmatter 完整
- 单文件未超 500 行,结构规范
Highlights
- 工具来源明确(nltk、rouge_score、bert_score、scipy、sklearn 等)
- 参数正确,覆盖主要异常(如统计检验、评分者一致性)
- 不可逆操作有确认机制(如回归检测阈值)
The arithmetic mean of the first four original scores, rounded to a whole number.
Static text checks
100 / 100 · skillpi-20261123-no-r3-v1
No current rules matched the text.
This score reflects rule matches in the text and is provided for reference before use. It excludes attachments and runtime behavior.
Permissions and checks before use
Automatically summarized from this main document. Matches may be examples or defensive advice; they are not actual permission declarations. Attachments, external dependencies and runtime behavior are not covered.
These common operations were not identified in the main document. This does not mean no permissions or risks exist.
Security rating and access scope
safe · Static evidence review; not a runtime safety guarantee.
Before use, confirm and authorize actual file access, external services and network destinations in your host. This review grants no runtime permissions.
User discussion
No verified reviews yet.