AI Prompt Engineering · 课时

分类中的置信度与不确定性

要求模型评估置信度,并处理含糊不清的分类

第 4 / 4 课13 个步骤

分类中的置信度与不确定性 是 CoddyKit 上的免费 AI Prompt Engineering 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 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
  • 监控生产环境中的不确定性比例——比例上升表示提示词退化或类别漂移
  • 始终针对已标注数据评估置信度校准——不只是评估准确率
免费开始

用 AI 导师学习 AI Prompt Engineering — 免费

在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。

课程
53
课程
199

常见问题解答

「分类中的置信度与不确定性」课时是免费的吗?

是的 — 「分类中的置信度与不确定性」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 AI Prompt Engineering 课程的其余内容,请升级到 CoddyKit PRO。 AI Prompt Engineering 课程共包含 4 节课。

「分类中的置信度与不确定性」这节课中我会学到什么?

要求模型评估置信度,并处理含糊不清的分类 你通过在浏览器中直接运行的动手代码来练习 AI Prompt Engineering,全天候 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