Semantic Similarity(语义相似度)
Semantic Similarity 指标评估生成回答与 reference(ground truth)答案之间的语义相似程度。范围为 0 到 1,分数越高表示生成答案与 ground truth 对齐得越好。
该指标使用 embeddings 和余弦相似度来衡量两个答案在语义上有多相似,这可以为生成回答的质量提供有价值的洞察。
示例
from openai import AsyncOpenAI
from ragas.embeddings import OpenAIEmbeddings
from ragas.metrics.collections import SemanticSimilarity
# Setup embeddings
client = AsyncOpenAI()
embeddings = OpenAIEmbeddings(model="text-embedding-3-small", client=client)
# Create metric
scorer = SemanticSimilarity(embeddings=embeddings)
# Evaluate
result = await scorer.ascore(
reference="The Eiffel Tower is located in Paris. It has a height of 1000ft.",
response="The Eiffel Tower is located in Paris."
)
print(f"Semantic Similarity Score: {result.value}")
输出:
Semantic Similarity Score: 0.8151
同步用法
如果你更喜欢同步代码,可以使用 .score() 方法代替 .ascore():
result = scorer.score(
reference="The Eiffel Tower is located in Paris. It has a height of 1000ft.",
response="The Eiffel Tower is located in Paris."
)
计算方式
示例
Reference:Albert Einstein's theory of relativity revolutionized our understanding of the universe.
高相似度回答:Einstein's groundbreaking theory of relativity transformed our comprehension of the cosmos.
低相似度回答:Isaac Newton's laws of motion greatly influenced classical physics.
让我们看看高相似度回答的 semantic similarity 是如何计算的:
- 步骤 1: 使用指定的 embedding 模型将 reference 答案向量化。
- 步骤 2: 使用同一 embedding 模型将生成的回答向量化。
- 步骤 3: 计算两个向量之间的余弦相似度。
- 步骤 4: 余弦相似度值(0-1)即为最终分数。
旧版 Metrics API
以下示例使用旧版 metrics API 模式。对于新项目,我们建议使用上文所示的 collections-based API。
弃用时间表
此 API 将在 0.4 版本中弃用,并在 1.0 版本中移除。请迁移到上文所示的 collections-based API。
使用 SingleTurnSample 的示例
from ragas.dataset_schema import SingleTurnSample
from ragas.metrics import SemanticSimilarity
from ragas.embeddings import LangchainEmbeddingsWrapper
sample = SingleTurnSample(
response="The Eiffel Tower is located in Paris.",
reference="The Eiffel Tower is located in Paris. It has a height of 1000ft."
)
scorer = SemanticSimilarity(embeddings=LangchainEmbeddingsWrapper(evaluator_embedding))
await scorer.single_turn_ascore(sample)
输出:
0.8151371879226978