从代码中可以看到,F1 Score的计算公式非常简洁:
def f1_score(precision, recall):
precision, recall = max(0.0, min(1.0, precision)), max(0.0, min(1.0, recall))
return 0.0 if precision + recall == 0 else 2 * (precision * recall) / (precision + recall)
数学公式: F1 = 2 × (Precision × Recall) / (Precision + Recall)
这实际上是 Precision 和 Recall 的调和平均数(Harmonic Mean)。
Precision(精确率/查准率)
Recall(召回率/查全率)
在您的代码中,SemanticF1 用于评估RAG系统的回答质量:
class SemanticRecallPrecision(Signature):
recall: float = OutputField(desc="fraction (out of 1.0) of ground truth covered by the system response")
precision: float = OutputField(desc="fraction (out of 1.0) of system response covered by the ground truth")
语义层面的理解:
F1 Score 解决了单独使用 Precision 或 Recall 的问题:
# 极端情况1:高Precision,低Recall
precision = 1.0, recall = 0.1 # 系统很谨慎,但遗漏很多
f1 = 2 * (1.0 * 0.1) / (1.0 + 0.1) = 0.18
# 极端情况2:低Precision,高Recall
precision = 0.1, recall = 1.0 # 系统回答很全,但有很多错误
f1 = 2 * (0.1 * 1.0) / (0.1 + 1.0) = 0.18
# 平衡情况:
precision = 0.8, recall = 0.8
f1 = 2 * (0.8 * 0.8) / (0.8 + 0.8) = 0.8
# 在DSPy中的实际使用
scores = self.module(
question=example.question,
ground_truth=example.response,
system_response=pred.response
)
score = f1_score(scores.precision, scores.recall)
高F1分数(0.8+):
中等F1分数(0.5-0.8):
低F1分数(<0.5):
def f1_score(precision, recall):
# 确保值在[0,1]范围内
precision, recall = max(0.0, min(1.0, precision)), max(0.0, min(1.0, recall))
# 避免除零错误
return 0.0 if precision + recall == 0 else 2 * (precision * recall) / (precision + recall)
关键特点:
从您的notebook可以看到:
# 记录F1分数作为主要评估指标
mlflow.log_metric("semantic_f1_score", result.score)
这使得您可以:
F1 Score 在RAG系统评估中是一个综合性的质量指标: