自己改善における評価と選択
生成されたプロンプトの優劣を評価し、最良のものを選ぶ方法を学びます。
「自己改善における評価と選択」はCoddyKit上の無料AI Prompt Engineeringレッスンです。 これはレッスン4/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応の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-as-Judge:多次元スコアリング
自由記述型のタスクでは、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))選択基準:品質、多様性、堅牢性
候補の中から最適なプロンプトを選ぶ際は、3つの側面を考慮します。品質(平均スコア)、多様性(現在のプロンプトとは異なるケースで失敗するか)、堅牢性(ケース間の分散が小さいか)です。
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プロンプトバージョン間の多様性の評価
平均スコアが同じ2つのプロンプトでも、まったく異なるケースで失敗することがあります。失敗したケースの集合を比較すると、新しいプロンプトが本当に相補的かどうかを判断できます。これはアンサンブルに役立ちます。
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.')確認問題
2つのプロンプトのバリエーションが、どちらも評価スイートで0.82のスコアを獲得しました。どちらを採用するか、どのように判断しますか。
評価と選択のまとめ
評価と選択は、効果的な自己改善ループの基盤です。
- 基準の設計:開始前に「より良い」とは何かを定義します。正確性、堅牢性、形式への準拠などです
- 多次元スコアリング:LLMジャッジが品質、関連性、明確さ、形式、安全性を個別に採点します
- 集計:平均だけでなく、平均、P10、P90を追跡します
- 選択:品質(平均スコア)と堅牢性(小さい分散)のバランスを取ります
- 最良のプロンプトの追跡:最新の反復だけでなく、履歴上の最良のプロンプトを常に保持します
- 停止条件:目標スコア、patience、最大反復回数、コスト予算を設定します
- 失敗集合の多様性:アンサンブルに適した相補的なプロンプトを特定します
AI チューターと学ぶ AI Prompt Engineering — 無料
ブラウザでリアルコードを書いて実行し、24/7 の AI チューターから瞬時にサポートを受け、ウェブまたはアプリで続きから学習できます。
- コース
- 53
- レッスン
- 199
よくある質問
「自己改善における評価と選択」レッスンは無料ですか?
はい。「自己改善における評価と選択」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、AI Prompt Engineeringコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 AI Prompt Engineeringコースには全4レッスンが含まれています。
「自己改善における評価と選択」で何を学びますか?
生成されたプロンプトの優劣を評価し、最良のものを選ぶ方法を学びます。 ブラウザで直接実行するハンズオンコードでAI Prompt Engineeringを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
AI Prompt Engineeringを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのAI Prompt Engineeringは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン4/4です。
「自己改善における評価と選択」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このAI Prompt Engineeringレッスンでコードを書いて実行できますか?
はい。すべてのAI Prompt Engineeringレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。
このコースのすべてのレッスン
- メタプロンプティングとは
- プロンプトを生成するプロンプト
- 自己改善型プロンプトシステム
- 自己改善における評価と選択