자기 개선에서의 평가와 선택
생성된 프롬프트 중 더 나은 것을 판단하고 우승 프롬프트를 선택하는 방법을 배웁니다.
자기 개선에서의 평가와 선택은(는) CoddyKit의 무료 AI Prompt Engineering 강의입니다. 이것은 4개 중 4번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 AI Prompt Engineering 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. AI Prompt Engineering 강의에는 총 4개의 강의가 포함되어 있습니다.
평가가 가장 어려운 이유
프롬프트 변형을 생성하는 일은 쉽습니다. 어떤 변형이 실제로 더 나은지 평가하는 일이 자기 개선에서 가장 어렵습니다. 엄격한 평가 없이는 다시 작성한 프롬프트가 실제로 개선된 것인지 단지 달라진 것인지 알 수 없습니다. 평가 품질이 전체 개선 루프의 품질을 결정합니다.
점수 기준 설계
자기 개선 루프를 실행하기 전에 작업에서 '더 낫다'는 것이 무엇을 의미하는지 정의합니다. 점수 기준은 객관적이고 측정 가능하며 작업의 성공 조건과 직접 연결되어야 합니다.
# Scoring criteria for different task types
SCORING_CRITERIA = {
'Classification': {
'primary_metric': 'Accuracy',
'formula': 'correct_predictions / total_predictions',
'secondary': ['Precision per class', 'F1 for rare classes'],
'target': 0.90
},
'Summarization': {
'primary_metric': 'LLM judge quality score',
'formula': 'average of judge scores on 1-5 scale, normalized to 0-1',
'secondary': ['ROUGE-L', 'Coverage of key facts', 'Hallucination rate'],
'target': 4.0 # on 1-5 scale
},
'Code generation': {
'primary_metric': 'Test pass rate',
'formula': 'tests_passing / total_tests',
'secondary': ['Syntax validity rate', 'Edge case coverage'],
'target': 0.85
},
'Information extraction': {
'primary_metric': 'F1 (precision + recall)',
'formula': '2 * precision * recall / (precision + recall)',
'secondary': ['Field-level accuracy', 'Format compliance rate'],
'target': 0.88
}
}
for task, criteria in SCORING_CRITERIA.items():
print(f'{task}: {criteria["primary_metric"]} (target: {criteria["target"]})')LLM 평가자: 다차원 점수 부여
개방형 작업에서는 LLM 평가자가 여러 품질 차원을 동시에 평가할 수 있습니다. 다차원 점수 부여는 단일 점수보다 더 풍부한 정보를 제공합니다.
import anthropic, json
client = anthropic.Anthropic(api_key='YOUR_API_KEY')
MULTI_DIM_JUDGE_PROMPT = '''Evaluate this AI response across 5 dimensions. Return JSON only.
Task description: {task}
User input: {input}
AI response: {response}
Score each dimension 1-5:
- accuracy: Is the information correct and complete?
- relevance: Does it address exactly what was asked?
- clarity: Is it clear and easy to understand for the target audience?
- format: Does it follow the required output format?
- safety: Does it avoid harmful, misleading, or inappropriate content?
Return: {{"accuracy": N, "relevance": N, "clarity": N,
"format": N, "safety": N, "overall": avg, "rationale": "<1 sentence>"}}'''
def judge_response(task, input_text, response, weights=None):
weights = weights or {'accuracy': 0.30, 'relevance': 0.25,
'clarity': 0.20, 'format': 0.15, 'safety': 0.10}
judge_result = client.messages.create(
model='claude-opus-4-5', max_tokens=300,
messages=[{'role': 'user', 'content':
MULTI_DIM_JUDGE_PROMPT.format(
task=task, input=input_text, response=response
)}]
)
scores = json.loads(judge_result.content[0].text)
weighted_score = sum(scores[dim] * w for dim, w in weights.items() if dim in scores)
scores['weighted_total'] = round(weighted_score, 2)
return scores검증 사례 전체의 점수 집계
프롬프트의 집계 점수는 전체 검증 모음에 대해 계산됩니다. 서로 다른 집계 전략을 사용하면 프롬프트 품질의 서로 다른 측면을 확인할 수 있습니다.
import statistics
def aggregate_scores(case_scores):
'''
case_scores: list of dicts with dimension scores per test case
'''
dimensions = ['accuracy', 'relevance', 'clarity', 'format', 'safety']
aggregated = {}
for dim in dimensions:
values = [s[dim] for s in case_scores if dim in s]
if not values:
continue
aggregated[dim] = {
'mean': round(statistics.mean(values), 2),
'min': min(values),
'max': max(values),
'stdev': round(statistics.stdev(values), 2) if len(values) > 1 else 0
}
# Overall weighted mean
overall_scores = [s.get('weighted_total', 0) for s in case_scores]
aggregated['overall'] = {
'mean': round(statistics.mean(overall_scores), 2),
'p10': round(sorted(overall_scores)[int(len(overall_scores)*0.10)], 2),
'p90': round(sorted(overall_scores)[int(len(overall_scores)*0.90)], 2)
}
return aggregated
# Example
sample_scores = [
{'accuracy': 4, 'relevance': 5, 'clarity': 4, 'format': 3, 'safety': 5, 'weighted_total': 4.1},
{'accuracy': 3, 'relevance': 4, 'clarity': 5, 'format': 4, 'safety': 5, 'weighted_total': 3.9},
]
print(aggregate_scores(sample_scores))선택 기준: 품질, 다양성, 견고성
후보 중에서 최적의 프롬프트를 선택할 때는 세 가지 차원을 고려해야 합니다: 품질(평균 점수), 다양성(현재 프롬프트와 다른 사례에서 실패하는가?), 견고성(사례별 분산이 낮은가).
def select_best_prompt(candidates, current_prompt_score):
'''
candidates: list of {prompt, scores, aggregated}
Returns the best candidate based on quality, diversity, robustness
'''
scored_candidates = []
for c in candidates:
agg = c['aggregated']['overall']
# Quality: mean score
quality = agg['mean']
# Robustness: inverse of P90-P10 spread (low spread = robust)
robustness = 1.0 - (agg['p90'] - agg['p10']) / 5.0
# Must beat current: reject if not better
if quality <= current_prompt_score:
continue
# Combined score
combined = 0.70 * quality + 0.30 * robustness
scored_candidates.append((combined, c))
if not scored_candidates:
print('No candidate beats current prompt. Keeping current.')
return None
scored_candidates.sort(reverse=True)
best = scored_candidates[0][1]
print(f'Selected candidate with combined score {scored_candidates[0][0]:.2f}')
return best['prompt']최고 성능 프롬프트 추적
개선 루프 전체에서 지금까지 확인한 프롬프트 중 가장 성능이 좋은 프롬프트를 항상 추적해야 합니다. 마지막 반복의 프롬프트가 반드시 최선은 아닙니다. 다시 작성하면서 일부 사례는 개선되지만 다른 사례에서는 회귀가 발생할 수 있기 때문입니다.
class BestPromptTracker:
def __init__(self):
self.best_score = -1
self.best_prompt = None
self.best_iteration = -1
self.all_scores = []
def update(self, iteration, prompt, score):
self.all_scores.append({'iteration': iteration, 'score': score})
if score > self.best_score:
self.best_score = score
self.best_prompt = prompt
self.best_iteration = iteration
print(f'New best at iteration {iteration}: score={score:.2f}')
else:
print(f'Iteration {iteration}: score={score:.2f} '
f'(best is still {self.best_score:.2f} at iter {self.best_iteration})')
def get_best(self):
return self.best_prompt, self.best_score, self.best_iteration
def is_converged(self, patience=2, min_delta=0.01):
if len(self.all_scores) < patience + 1:
return False
recent = self.all_scores[-(patience+1):]
improvement = recent[-1]['score'] - recent[0]['score']
return improvement < min_delta
tracker = BestPromptTracker()
for i, score in enumerate([0.65, 0.72, 0.78, 0.77, 0.79]):
tracker.update(i, f'prompt_v{i}', score)
print('Best:', tracker.get_best())중지 기준
언제 중지할지 아는 것은 언제 계속할지 아는 것만큼 중요합니다. 중지 기준이 좋지 않으면 API 예산을 낭비하거나 품질 목표에 도달하기 전에 너무 일찍 종료할 수 있습니다.
STOPPING_CONDITIONS = [
'Target score reached (e.g., >= 0.90)',
'No improvement over last N iterations (patience)',
'Maximum iteration budget exhausted',
'Score improvement delta below minimum threshold',
'All test cases pass (score = 1.0)',
'Cost budget exceeded'
]
def should_stop(tracker, config):
_, best_score, _ = tracker.get_best()
# Condition 1: Target reached
if best_score >= config['target_score']:
return True, f'Target score {config["target_score"]} reached'
# Condition 2: Patience exhausted
if tracker.is_converged(patience=config['patience'],
min_delta=config['min_delta']):
return True, f'No improvement over {config["patience"]} iterations'
# Condition 3: Max iterations
if len(tracker.all_scores) >= config['max_iterations']:
return True, f'Max iterations {config["max_iterations"]} reached'
return False, 'Continue'
config = {'target_score': 0.90, 'patience': 3,
'min_delta': 0.01, 'max_iterations': 10}
stop, reason = should_stop(tracker, config)
print(f'Stop: {stop} | Reason: {reason}')자기 개선을 위한 검증 모음 설계
자기 개선 루프의 품질은 검증 모음의 품질에 달려 있습니다. 잘 설계된 검증 모음은 일반 사례, 극단적 사례, 적대적 사례를 포괄하며 안정적으로 유지되어야 합니다(루프 실행 중에는 업데이트하지 않음).
def design_test_suite_for_improvement(task_description, target_size=50):
'''
Generate a balanced test suite for prompt self-improvement loops.
The suite is fixed and does not change during iterations.
'''
distribution = {
'typical': int(target_size * 0.50), # 50% typical cases
'edge_case': int(target_size * 0.25), # 25% edge cases
'adversarial': int(target_size * 0.15), # 15% adversarial
'off_topic': int(target_size * 0.10) # 10% off-topic (guardrails)
}
print('Test suite distribution:')
for category, count in distribution.items():
print(f' {category}: {count} cases')
# Key properties of a good evaluation test suite:
properties = [
'Fixed (never modified during improvement loop)',
'Balanced across difficulty levels',
'Has ground truth labels / expected outputs',
'Diverse in topic and phrasing within each category',
'Held-out: separate from any few-shot examples in the prompt'
]
for p in properties:
print(f' Property: {p}')
return distribution프롬프트 버전 간 다양성 평가
평균 점수가 같은 두 프롬프트가 완전히 다른 사례에서 실패할 수 있습니다. 두 프롬프트의 실패 집합을 비교하면 새 프롬프트가 실제로 상호 보완적인지, 즉 앙상블에 유용한지 확인할 수 있습니다.
def compare_failure_sets(prompt_a_results, prompt_b_results):
'''
Compare which cases each prompt fails on.
'''
fails_a = {r['case_id'] for r in prompt_a_results if not r['correct']}
fails_b = {r['case_id'] for r in prompt_b_results if not r['correct']}
both_fail = fails_a & fails_b
only_a_fails = fails_a - fails_b
only_b_fails = fails_b - fails_a
overlap = len(both_fail) / max(len(fails_a | fails_b), 1)
print(f'Prompt A failures: {len(fails_a)}')
print(f'Prompt B failures: {len(fails_b)}')
print(f'Both fail: {len(both_fail)} (overlap: {overlap:.0%})')
print(f'Only A fails: {len(only_a_fails)}')
print(f'Only B fails: {len(only_b_fails)}')
if overlap < 0.3:
print('LOW overlap — prompts are complementary. Consider ensembling.')
else:
print('HIGH overlap — B is a refinement of A, not a different approach.')
return {'overlap': overlap, 'only_a': only_a_fails, 'only_b': only_b_fails}보정: 평가자 점수를 신뢰할 수 있나요?
LLM 평가자의 점수는 실제 품질과 상관관계가 있을 때만 유용합니다. 보정은 기준 예시 집합에 대한 평가자의 점수가 사람의 평가와 일치하는지 확인합니다.
def calibrate_judge(judge_fn, gold_standard):
'''
gold_standard: list of {input, response, human_score} dicts
Returns correlation between judge scores and human scores.
'''
import statistics
judge_scores = []
human_scores = []
for example in gold_standard:
judge_score = judge_fn(
task='General response quality',
input_text=example['input'],
response=example['response']
)
judge_scores.append(judge_score)
human_scores.append(example['human_score'])
# Pearson correlation
n = len(judge_scores)
mean_j = statistics.mean(judge_scores)
mean_h = statistics.mean(human_scores)
cov = sum((j - mean_j) * (h - mean_h) for j, h in zip(judge_scores, human_scores))
std_j = statistics.stdev(judge_scores)
std_h = statistics.stdev(human_scores)
if std_j == 0 or std_h == 0:
return 0.0
correlation = cov / ((n - 1) * std_j * std_h)
print(f'Judge-Human correlation: {correlation:.3f}')
if correlation < 0.7:
print('WARNING: Low correlation. Judge may not reflect human quality judgment.')
return correlation앙상블 접근 방식: 최적의 프롬프트 결합
여러 프롬프트 변형이 서로 다른 사례에서 실패할 때 다수결이나 신뢰도 가중치를 사용하여 결합하면 단일 프롬프트보다 높은 품질을 얻을 수 있습니다.
def ensemble_prompts(prompts, test_input, model='claude-haiku-4-5'):
'''
Run multiple prompts on the same input and take majority vote.
'''
outputs = []
for i, prompt in enumerate(prompts):
response = client.messages.create(
model=model, max_tokens=300,
messages=[{'role': 'user', 'content':
prompt + '\n\nInput: ' + test_input}]
)
outputs.append(response.content[0].text.strip())
# Majority vote for classification
from collections import Counter
vote_counts = Counter(outputs)
majority = vote_counts.most_common(1)[0][0]
confidence = vote_counts[majority] / len(outputs)
print(f'Ensemble ({len(prompts)} prompts): {majority} ({confidence:.0%} agreement)')
return majority, confidence
# When to use ensemble vs. single best prompt:
# - Ensemble: high-stakes classification, tolerate 3x API cost
# - Single best: cost-sensitive production, latency-critical
print('Ensemble is costlier but more robust for high-stakes outputs.')빠른 확인
두 프롬프트 변형이 모두 평가 모음에서 0.82점을 얻었습니다. 어느 변형을 채택할지 어떻게 결정하시겠습니까?
평가 및 선택 요약
평가와 선택은 효과적인 자기 개선 루프의 토대입니다:
- 기준 설계: 시작하기 전에 '더 낫다'는 의미를 정의합니다. 정확도, 견고성, 형식 준수 등이 해당합니다.
- 다차원 점수 부여: LLM 평가자가 품질, 관련성, 명확성, 형식, 안전성을 독립적으로 평가합니다.
- 집계: 평균만이 아니라 평균, P10, P90을 추적합니다.
- 선택: 품질(평균 점수)과 견고성(낮은 분산)의 균형을 맞춥니다.
- 최고 프롬프트 추적: 최신 반복뿐 아니라 과거의 최고 프롬프트를 항상 유지합니다.
- 중지 기준: 목표 점수, 대기 횟수, 최대 반복 횟수, 비용 예산
- 실패 집합의 다양성: 앙상블을 위한 상호 보완적인 프롬프트 식별
AI 튜터와 함께 AI Prompt Engineering을(를) 배우세요 — 무료
브라우저에서 실제 코드를 작성하고 실행하며, 24/7 AI 튜터로부터 즉각적인 도움을 받고, 웹이나 앱에서 중단한 부분부터 계속 학습하세요.
- 코스
- 53
- 레슨
- 199
자주 묻는 질문
“자기 개선에서의 평가와 선택” 강의는 무료인가요?
네 — “자기 개선에서의 평가와 선택” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 AI Prompt Engineering 강의 전체를 잠금 해제할 수 있습니다. AI Prompt Engineering 강의에는 총 4개의 강의가 포함되어 있습니다.
“자기 개선에서의 평가와 선택”에서 뭘 배우나요?
생성된 프롬프트 중 더 나은 것을 판단하고 우승 프롬프트를 선택하는 방법을 배웁니다. 브라우저에서 직접 실행하는 실습 코드로 AI Prompt Engineering을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
AI Prompt Engineering을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 AI Prompt Engineering은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 4번째 강의입니다.
“자기 개선에서의 평가와 선택” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 AI Prompt Engineering 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 AI Prompt Engineering 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 메타 프롬프트란 무엇인가요?
- 프롬프트를 생성하는 프롬프트
- 스스로 개선하는 프롬프트 시스템
- 자기 개선에서의 평가와 선택