답변 정확성(Answer correctness)

답변 정확성(Answer correctness)

답변 정확성은 생성된 답변이 정답(ground truth)과 얼마나 가까운지 측정하는 지표예요. ground truthanswer를 비교해 0~1 점수로 나타내며, 점수가 높을수록 정답에 더 가깝고 정확도가 높다는 뜻이에요. 두 답변의 '의미가 얼마나 비슷한가'와 '사실이 얼마나 일치하는가'를 함께 보는 지표라서 신뢰도가 높아요.

출처: 문서

본문

답변 정확성(Answer Correctness)

답변 정확성 평가는 생성된 답변이 정답(ground truth)과 비교했을 때 얼마나 정확한지 가늠하는 거예요. 이 평가는 ground truthanswer에 의존하며 점수는 0에서 1 사이예요. 점수가 높을수록 생성된 답변이 정답에 더 가깝게 정렬되어 더 나은 정확성을 의미해요.

답변 정확성은 생성된 답변과 정답 사이의 의미적 유사성(semantic similarity)과 사실적 유사성(factual similarity)이라는 두 가지 중요한 측면을 포괄해요. 이 측면들은 가중 방식으로 결합되어 답변 정확성 점수를 구성해요. 원하면 '임계값(threshold)'을 사용해 결과 점수를 이진으로 반올림할 수도 있어요.

임베딩 요구사항(Embedding Requirement) AnswerCorrectness는 의미적 유사성 계산을 위해 임베딩이 필요해요. evaluate()를 임베딩을 명시적으로 제공하지 않고 사용하면, Ragas가 임베딩 제공자를 LLM 제공자에 자동으로 맞춰요. 예를 들어 LLM으로 Gemini를 사용하면 Google 임베딩이 자동으로 쓰여요(OpenAI API 키 불필요). 완전한 제어를 위해 임베딩을 명시적으로 제공할 수도 있어요.

예시(Example) Ground truth: Einstein was born in 1879 in Germany. 높은 답변 정확성: In 1879, Einstein was born in Germany. 낮은 답변 정확성: Einstein was born in Spain in 1879.

예시(Example)

from openai import AsyncOpenAI
from ragas.llms import llm_factory
from ragas.embeddings.base import embedding_factory
from ragas.metrics.collections import AnswerCorrectness

# Setup LLM and embeddings
client = AsyncOpenAI()
llm = llm_factory("gpt-4o-mini", client=client)
embeddings = embedding_factory("openai", model="text-embedding-3-small", client=client)

# Create metric
scorer = AnswerCorrectness(llm=llm, embeddings=embeddings)

# Evaluate
result = await scorer.ascore(
    user_input="When was the first super bowl?",
    response="The first superbowl was held on Jan 15, 1967",
    reference="The first superbowl was held on January 15, 1967"
)
print(f"Answer Correctness Score: {result.value}")

출력(Output):

Answer Correctness Score: 0.95

동기 사용법(Synchronous Usage) 동기 코드를 선호한다면 .ascore() 대신 .score() 메서드를 쓸 수 있어요: result = scorer.score( user_input="When was the first super bowl?", response="The first superbowl was held on Jan 15, 1967", reference="The first superbowl was held on January 15, 1967" )

계산(Calculation)

낮은 답변 정확성을 가진 답변에 대해 답변 정확성을 계산해볼게요. 이는 사실적 정확성과 주어진 답변 및 정답 사이의 의미적 유사성의 합으로 계산돼요.

사실적 정확성(Factual correctness)은 생성 답변과 정답 사이의 사실적 겹침을 정량화해요. 다음 개념을 사용해요:

  • TP (True Positive): 정답과 생성 답변 양쪽에 모두 존재하는 사실 또는 진술.
  • FP (False Positive): 생성 답변에는 있지만 정답에는 없는 사실 또는 진술.
  • FN (False Negative): 정답에는 있지만 생성 답변에는 없는 사실 또는 진술.

두 번째 예시에서:

  • TP: [Einstein was born in 1879]
  • FP: [Einstein was born in Spain]
  • FN: [Einstein was born in Germany]

이제 F1 점수 공식을 사용해 각 목록의 진술 수에 기반해 정확성을 정량화할 수 있어요:

[ \text{F1 Score} = {|\text{TP} \over {(|\text{TP}| + 0.5 \times (|\text{FP}| + |\text{FN}|))}} ]

다음으로 생성 답변과 정답 사이의 의미적 유사성을 계산해요. 더 자세한 내용은 여기에서 읽어보세요.

의미적 유사성을 구하면, 위에서 계산한 의미적 유사성과 사실적 유사성의 가중 평균을 내 최종 점수를 도출해요. weights 파라미터를 수정해 이 가중치를 조정할 수 있어요.

레거시 지표 API(Legacy Metrics API)

다음 예시는 레거시 지표 API 패턴을 사용해요. 새 프로젝트에는 위에서 보여준 컬렉션 기반 API를 권장해요.

폐지 일정(Deprecation Timeline) 이 API는 버전 0.4에서 폐지되고 버전 1.0에서 제거될 예정이에요. 위에 보여준 컬렉션 기반 API로 마이그레이션해주세요.

데이터셋과 함께하는 예시(Example with Dataset)

from datasets import Dataset 
from ragas.metrics import answer_correctness
from ragas import evaluate

data_samples = {
    'question': ['When was the first super bowl?', 'Who won the most super bowls?'],
    'answer': ['The first superbowl was held on Jan 15, 1967', 'The most super bowls have been won by The New England Patriots'],
    'ground_truth': ['The first superbowl was held on January 15, 1967', 'The New England Patriots have won the Super Bowl a record six times']
}
dataset = Dataset.from_dict(data_samples)
score = evaluate(dataset,metrics=[answer_correctness])
score.to_pandas()

더 알아보기 (Learn more)