0Pricing
AI Prompt Engineering · 강의

분류의 확신도와 불확실성

모델에 확신도를 점수로 매기게 하고 모호한 분류를 처리하도록 요청합니다.

분류의 확신도와 불확실성은(는) CoddyKit의 무료 AI Prompt Engineering 강의입니다. 이것은 4개 중 4번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 AI Prompt Engineering 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. AI Prompt Engineering 강의에는 총 4개의 강의가 포함되어 있습니다.

과도하게 확신하는 모델의 문제

기본적으로 LLM은 입력이 실제로 모호한 경우에도 겉보기에는 확신에 찬 태도로 분류 작업에 답합니다. 긍정, 부정 또는 중립을 반환하라고 지시받은 모델은 항상 하나를 선택하며 잘 모르겠습니다라고 말하지 않습니다.

운영 시스템에서 불확실한 분류를 확실한 것으로 간주하고 처리하면 비용이 큰 오류가 발생합니다. 지원 요청이 잘못된 곳으로 전달되고, 추천이 잘못되며, 보고서가 부정확해질 수 있습니다.

분류 프롬프트에 불확실성 정량화를 적용하면 이 문제를 해결할 수 있습니다.

신뢰도 점수 1~10

모델에 숫자 척도로 신뢰도를 평가하도록 요청하면 후속 시스템에서 임계값을 설정할 수 있는 세밀한 신호를 얻을 수 있습니다:

import anthropic, json

client = anthropic.Anthropic(api_key='YOUR_API_KEY')

def classify_with_confidence(text):
    prompt = f'''
Classify the sentiment of the text below.
Return JSON:
{{
  "sentiment": "positive|negative|neutral",
  "confidence": 1-10,
  "reason": "brief explanation of confidence level"
}}

Confidence scale: 10=completely certain, 1=total guess, 5=genuinely ambiguous

Text: {text}
'''
    r = client.messages.create(
        model='claude-opus-4-5', max_tokens=100,
        messages=[{'role': 'user', 'content': prompt}]
    )
    return json.loads(r.content[0].text)

print(classify_with_confidence('I sort of liked it but the wait was too long.'))
print(classify_with_confidence('This product is absolutely outstanding!'))

UNCERTAIN 응답

분류 신뢰도가 임계값보다 낮을 때 UNCERTAIN이라고 명시적으로 응답하도록 지시하면 긍정, 부정 또는 UNCERTAIN이라는 세 가지 출력이 만들어집니다:

def classify_or_uncertain(text, uncertainty_threshold=4):
    prompt = f'''
Classify the sentiment of the text: positive, negative, or neutral.

If the sentiment is genuinely ambiguous or you are not confident (confidence below {uncertainty_threshold}/10),
return UNCERTAIN instead of guessing.

Return JSON: {{"sentiment": "positive|negative|neutral|UNCERTAIN", "confidence": 1-10}}

Text: {text}
'''
    r = client.messages.create(
        model='claude-opus-4-5', max_tokens=80,
        messages=[{'role': 'user', 'content': prompt}]
    )
    result = json.loads(r.content[0].text)

    if result['sentiment'] == 'UNCERTAIN' or result['confidence'] < uncertainty_threshold:
        print(f'Routing to human review: confidence={result["confidence"]}')
    return result

print(classify_or_uncertain('It was fine, I guess. Not bad, not great.'))
print(classify_or_uncertain('Absolutely terrible product. Never buying again.'))

순위가 매겨진 범주 확률

하나의 범주를 억지로 선택하게 하는 대신, 가능한 모든 범주의 순위를 가능성에 따라 매기도록 모델에 요청하세요. 상위 두 범주가 얼마나 근접한지 확인할 수 있습니다:

def classify_ranked(text, categories):
    cats = ', '.join(categories)
    prompt = f'''
Classify this text into one of these categories: {cats}

Return ALL categories ranked by likelihood, highest first.
Return JSON: {{"ranked": [{{"category": str, "probability": 0.0-1.0}}]}}
Probabilities must sum to 1.0.

Text: {text}
'''
    r = client.messages.create(
        model='claude-opus-4-5', max_tokens=150,
        messages=[{'role': 'user', 'content': prompt}]
    )
    result = json.loads(r.content[0].text)
    return result['ranked']

cats = ['billing', 'technical', 'general', 'cancellation']
ranked = classify_ranked('I was charged twice and now my account is locked.', cats)
for item in ranked:
    print(f'{item["category"]}: {item["probability"]:.0%}')

확률 차이를 사용한 모호성 감지

순위가 매겨진 상위 두 확률의 차이는 신뢰할 수 있는 모호성 신호입니다. 차이가 작으면 모델이 불확실하다는 뜻이고, 차이가 크면 확신하고 있다는 뜻입니다:

def classify_with_ambiguity_detection(text, categories, ambiguity_threshold=0.15):
    ranked = classify_ranked(text, categories)

    top1_prob = ranked[0]['probability']
    top2_prob = ranked[1]['probability'] if len(ranked) > 1 else 0
    spread = top1_prob - top2_prob

    is_ambiguous = spread < ambiguity_threshold

    return {
        'primary': ranked[0]['category'],
        'secondary': ranked[1]['category'] if len(ranked) > 1 else None,
        'confidence_spread': round(spread, 3),
        'is_ambiguous': is_ambiguous,
        'action': 'human_review' if is_ambiguous else 'auto_classify'
    }

result = classify_with_ambiguity_detection(
    'My upgrade did not apply and I think I was still charged.', ['billing', 'technical', 'general', 'cancellation']
)
print(result)

조건부 불확실성: 확실하지 않으면 질문하기

대화형 애플리케이션에서는 UNCERTAIN을 반환하는 대신 모델이 명확히 해 달라고 질문할 수 있습니다:

SYSTEM_CLARIFY = '''
You are a support ticket classifier.
If the customer message is clear, classify it and respond with JSON:
{"action": "classify", "category": str, "confidence": 1-10}

If the message is ambiguous or you are not sure which category applies, respond with:
{"action": "clarify", "question": "A single clarifying question to ask the customer"}

Categories: billing, technical, account, cancellation

Only ask for clarification when genuinely needed. Prefer classification when possible.
'''

def classify_or_ask(message):
    r = client.messages.create(
        model='claude-opus-4-5', max_tokens=100,
        system=SYSTEM_CLARIFY,
        messages=[{'role': 'user', 'content': message}]
    )
    return json.loads(r.content[0].text)

print(classify_or_ask('It is not working anymore.'))
print(classify_or_ask('Cancel my subscription immediately.'))

신뢰도 보정: 온도와 일관성

동일한 분류를 서로 다른 온도 설정에서 여러 번 실행하면 모델의 실제 불확실성이 드러납니다. 분산이 높다는 것은 입력이 실제로 모호하다는 뜻입니다:

from collections import Counter

def calibrated_classify(text, n_samples=5):
    results = []
    for _ in range(n_samples):
        r = client.messages.create(
            model='claude-opus-4-5', max_tokens=50,
            messages=[{'role': 'user', 'content': f'Classify as positive/negative/neutral. Return JSON: {{"sentiment": str}}\n\n{text}'}]
        )
        results.append(json.loads(r.content[0].text)['sentiment'])

    counts = Counter(results)
    dominant = counts.most_common(1)[0]
    agreement_rate = dominant[1] / n_samples

    return {
        'classification': dominant[0],
        'agreement_rate': agreement_rate,
        'is_uncertain': agreement_rate < 0.7,
        'all_results': dict(counts)
    }

result = calibrated_classify('The product is okay, nothing special.')
print(result)

신뢰도에 따른 분기

운영 환경의 분기 시스템은 신뢰도 수준을 사용해 서로 다른 처리기로 분기합니다:

def route_by_confidence(text, classify_fn, auto_threshold=8, human_threshold=4):
    result = classify_fn(text)
    confidence = result.get('confidence', 5)
    category = result.get('category') or result.get('sentiment', 'unknown')

    if confidence >= auto_threshold:
        return {'route': 'auto_process', 'category': category, 'confidence': confidence}
    elif confidence >= human_threshold:
        return {'route': 'auto_process_with_flag', 'category': category, 'confidence': confidence,
                'flag': 'Low confidence — monitor output'}
    else:
        return {'route': 'human_review', 'category': category, 'confidence': confidence,
                'flag': 'Very low confidence — human classification required'}

print(route_by_confidence('Hate this product.', classify_with_confidence))
print(route_by_confidence('It is kind of okay but also not really.', classify_with_confidence))

구조화된 불확실성 항목

분류 출력에 사용할 수 있는 포괄적인 불확실성 스키마입니다:

UNCERTAINTY_SCHEMA = '''
Return JSON:
{
  "primary_category": "string",
  "confidence": 1-10,
  "uncertainty_type": "none | ambiguous_input | insufficient_context | boundary_case | none",
  "alternative_categories": ["string"] or [],
  "uncertainty_explanation": "string or null",
  "recommended_action": "auto_classify | human_review | request_more_info"
}

Uncertainty types:
- ambiguous_input: The text could clearly mean multiple things
- insufficient_context: Need more information to classify correctly
- boundary_case: The text sits on the border between two categories
- none: Clear classification, no uncertainty
'''

print(UNCERTAINTY_SCHEMA)
print('Use this schema for any classification task requiring uncertainty quantification.')

운영 환경에서 불확실성 추적

운영 환경에서 불확실성 비율을 모니터링하여 프롬프트 품질 저하나 범주 변화를 감지하세요:

class ClassificationMonitor:
    def __init__(self, human_review_threshold=0.15):
        self.total = 0
        self.uncertain = 0
        self.threshold = human_review_threshold
        self.category_counts = {}

    def record(self, result):
        self.total += 1
        cat = result.get('category', 'unknown')
        self.category_counts[cat] = self.category_counts.get(cat, 0) + 1

        if result.get('confidence', 10) < 5 or result.get('sentiment') == 'UNCERTAIN':
            self.uncertain += 1

    def report(self):
        uncertain_rate = self.uncertain / self.total if self.total else 0
        alert = uncertain_rate > self.threshold
        return {
            'total': self.total,
            'uncertain_rate': round(uncertain_rate, 3),
            'alert': alert,
            'category_distribution': self.category_counts
        }

monitor = ClassificationMonitor()
print('Production monitoring system defined.')

높은 신뢰도를 언제 믿을 것인가

모델의 신뢰도가 높다고 해서 분류가 항상 올바른 것은 아닙니다. 높은 신뢰도에서도 나타나는 일반적인 실패 방식은 다음과 같습니다:

  • 체계적 편향: 모델이 특정 패턴을 높은 신뢰도의 오답으로 일관되게 잘못 분류함
  • 도메인 변화: 모델은 확신하지만 입력 양식이 학습 데이터와 매우 다름
  • 아첨 성향: 모델이 실제 확실성이 아니라 듣기 좋은 내용에 맞춰 신뢰도를 조정함

항상 레이블이 지정된 검증 세트를 기준으로 신뢰도 보정을 평가하세요 — 정확도뿐 아니라 신뢰도가 높은 예측이 낮은 예측보다 실제로 더 정확한지도 평가해야 합니다.

간단 확인

분류 결과에서 순위가 매겨진 상위 두 범주 확률의 차이가 작다는 것은 무엇을 의미하나요?

분류의 불확실성 — 핵심 요점

불확실성 정량화는 분류를 불투명한 시스템에서 관리 가능한 시스템으로 바꿉니다:

  • 모든 분류에 신뢰도 점수(1~10)를 요청하세요 — 출력 결과를 모두 똑같이 신뢰할 수 있다고 간주하지 마세요
  • 실제로 모호한 입력에는 범주를 억지로 선택하게 하는 대신 UNCERTAIN 응답을 사용하세요
  • 모든 범주의 순위를 확률에 따라 매기세요 — 상위 두 범주의 차이가 가장 좋은 모호성 신호입니다
  • 신뢰도가 임계값보다 낮으면 사람의 검토로 보내고, 높으면 자동으로 처리하세요
  • 대화형 앱에서는 UNCERTAIN을 반환하는 대신 명확히 하기 위한 질문을 하세요
  • 운영 환경에서 불확실성 비율을 모니터링하세요 — 비율 상승은 프롬프트 품질 저하나 범주 변화를 의미합니다
  • 항상 레이블이 지정된 데이터를 기준으로 신뢰도 보정을 평가하세요 — 정확도만 평가해서는 안 됩니다

자주 묻는 질문

“분류의 확신도와 불확실성” 강의는 무료인가요?

네 — “분류의 확신도와 불확실성” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 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 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 명명된 개체 추출 프롬프트
  2. 스키마 기반 데이터 추출
  3. 텍스트 분류기로서의 LLM
  4. 분류의 확신도와 불확실성
← AI Prompt Engineering(으)로 돌아가기