0Pricing
AI Prompt Engineering · 강의

텍스트 분류기로서의 LLM

감성, 의도, 주제 및 다중 레이블 분류에 프롬프트를 활용합니다.

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

텍스트 분류기로서의 LLM

기존 텍스트 분류에는 레이블이 지정된 학습 데이터, 모델 미세 조정, 배포 인프라가 필요합니다. LLM은 학습 데이터 없이 프롬프트만으로 텍스트를 분류할 수 있습니다.

LLM 기반 분류기는 다음과 같은 경우에 뛰어난 성능을 보입니다:

  • 범주를 판단하려면 단순한 키워드 일치가 아니라 의미 이해가 필요한 경우
  • 재학습 없이 새로운 범주를 추가해야 하는 경우
  • 레이블이 지정된 예시가 제한적인 경우
  • 범주가 세분화되어 있는 경우(단순한 주제가 아니라 메시지에 담긴 의도를 분류해야 하는 경우)

감정 분류

감정은 가장 일반적인 분류 작업 중 하나입니다. 잘 작성된 프롬프트는 미묘한 사례에서 단순한 키워드 일치보다 더 뛰어난 성능을 보입니다:

import anthropic, json

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

def classify_sentiment(text):
    prompt = f'''
Classify the sentiment of the text below.
Return ONLY JSON: {{"sentiment": "positive|negative|neutral", "confidence": "high|medium|low"}}

Definitions:
- positive: Overall favorable opinion or emotion
- negative: Overall unfavorable opinion or dissatisfaction
- neutral: Factual, balanced, or no clear sentiment

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

print(classify_sentiment('The product works but setup was painful.'))
print(classify_sentiment('Delivery was incredibly fast and packaging was perfect!'))

의도 분류

의도 분류는 사용자가 무엇을 하려는지 식별하는 작업으로, 챗봇, 지원 시스템, 검색 애플리케이션에 필수적입니다:

INTENT_CATEGORIES = [
    'purchase_intent: User wants to buy or is ready to purchase',
    'complaint: User is dissatisfied and reporting a problem',
    'question: User is asking for information or help',
    'cancellation: User wants to cancel a service or subscription',
    'compliment: User is expressing satisfaction or praise',
    'other: Does not fit any category above'
]

def classify_intent(message):
    categories_str = '\n'.join(f'- {c}' for c in INTENT_CATEGORIES)
    prompt = f'''
Classify the intent of this customer message.
Return JSON: {{"intent": str, "confidence": "high|medium|low"}}

Categories:
{categories_str}

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

print(classify_intent('I love the app but I need to cancel my plan.'))
print(classify_intent('How do I export my data to CSV?'))

주제 분류

주제 분류는 텍스트에 주제별 범주를 할당합니다. 콘텐츠를 적절한 경로로 보내고, 피드를 필터링하며, 지원 요청을 분류하는 데 유용합니다:

def classify_topic(article_text, topics):
    topic_list = ', '.join(topics)
    prompt = f'''
Classify the topic of this article. Choose EXACTLY ONE from the list.
Return JSON: {{"topic": str, "secondary_topic": str or null}}

Available topics: {topic_list}

Article (first 300 chars): {article_text[:300]}
'''
    r = client.messages.create(model='claude-opus-4-5', max_tokens=80, messages=[{'role': 'user', 'content': prompt}])
    return json.loads(r.content[0].text)

topics = ['technology', 'sports', 'politics', 'business', 'science', 'health', 'entertainment']
text = 'The FDA approved a new mRNA vaccine for seasonal influenza, marking a breakthrough in vaccine technology.'
result = classify_topic(text, topics)
print(result)

긴급도 분류

긴급도 분류는 지원 요청, 이메일, 사건의 우선순위를 정하는 데 도움이 됩니다. 긴급도 수준을 정확하게 정의하는 것이 중요합니다:

URGENCY_PROMPT = '''
Classify the urgency of this support ticket.
Return JSON: {{"urgency": str, "reason": str}}

Urgency levels:
- critical: Service is completely down, data loss occurring, or security breach
- high: Major functionality broken, many users affected, no workaround
- medium: Non-critical feature broken, workaround exists, single user affected
- low: Cosmetic issue, enhancement request, general question

Be conservative: only use critical if the ticket explicitly describes a system-wide outage or data loss.

Ticket: {ticket}
'''

def classify_urgency(ticket_text):
    prompt = URGENCY_PROMPT.replace('{ticket}', ticket_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_urgency('The entire production database is down. All customers affected.'))
print(classify_urgency('Dark mode button is slightly off-center.'))

다중 레이블 분류

텍스트가 여러 범주에 동시에 속하는 경우가 있습니다. 다중 레이블 분류는 해당하는 모든 범주를 반환합니다:

def multi_label_classify(text, labels):
    label_list = ', '.join(labels)
    prompt = f'''
Classify this text. It may belong to multiple categories.
Return JSON: {{"labels": [str], "primary_label": str}}

Available labels: {label_list}

Rules:
- Include all labels that clearly apply
- Do NOT include labels that only marginally apply
- primary_label is the single most relevant label

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)

labels = ['technical', 'billing', 'account', 'bug_report', 'feature_request', 'security']
text = 'I found a bug that exposes other users billing information on my account page.'
print(multi_label_classify(text, labels))

분류 프롬프트 서식

모든 범주 집합에 사용할 수 있는 재사용 가능한 분류 프롬프트 서식입니다:

def build_classifier(category_definitions, additional_rules=''):
    cats = '\n'.join(f'- {k}: {v}' for k, v in category_definitions.items())
    return f'''
Classify the input text into exactly one category below.
Return JSON: {{"category": str, "confidence": "high|medium|low"}}

Categories:
{cats}
{('\nAdditional rules:\n' + additional_rules) if additional_rules else ''}

Text: {{text}}
'''

language_classifier = build_classifier({
    'formal': 'Business or academic writing, professional context',
    'informal': 'Casual, conversational, slang or colloquial',
    'technical': 'Domain-specific jargon, code, or specialized terminology',
    'emotional': 'High emotional content, personal, expressive'
})

print(language_classifier[:200])

모호한 분류 처리

일부 입력은 실제로 여러 범주에 잘 맞습니다. 모호성을 명시적으로 처리하도록 분류 프롬프트를 설계하세요:

AMBIGUITY_PROMPT = '''
Classify this customer message. If the message is ambiguous or could fit multiple categories,
choose the category that would be most useful for routing it to the correct team.

Return JSON:
{{
  "category": str,
  "is_ambiguous": true | false,
  "alternative": str or null,
  "reasoning": str
}}

Categories: billing, technical_support, sales, account_management

Message: {message}
'''

message = 'I upgraded my plan but I am still seeing the free tier features.'
r = client.messages.create(
    model='claude-opus-4-5', max_tokens=150,
    messages=[{'role': 'user', 'content': AMBIGUITY_PROMPT.format(message=message)}]
)
print(json.loads(r.content[0].text))

효율적인 일괄 분류

항목을 하나씩 분류하면 비용이 많이 듭니다. 일괄 분류는 하나의 API 호출로 여러 입력을 처리합니다:

def batch_classify(items, categories):
    items_str = '\n'.join(f'{i+1}. {item}' for i, item in enumerate(items))
    cat_str = ', '.join(categories)

    prompt = f'''
Classify each item below. Categories: {cat_str}
Return JSON: {{"results": [{{"id": int, "category": str, "confidence": str}}]}}

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

texts = [
    'Absolutely love this product!',
    'It crashed twice today.',
    'What is your refund policy?',
    'The color options are limited.'
]
results = batch_classify(texts, ['positive_feedback', 'bug_report', 'inquiry', 'feature_request'])
for r in results:
    print(f'{texts[r["id"]-1][:30]}... -> {r["category"]} ({r["confidence"]})')

분류기 정확도 평가

LLM 분류기는 레이블이 지정된 예시를 기준으로 체계적으로 평가해야 합니다. 작은 검증 세트를 만들고 정확도를 측정하세요:

labeled_test_set = [
    {'text': 'Great product, no issues!', 'expected': 'positive'},
    {'text': 'The app keeps crashing on startup.', 'expected': 'negative'},
    {'text': 'The screen resolution is 1080p.', 'expected': 'neutral'},
    {'text': 'Worst experience of my life.', 'expected': 'negative'},
    {'text': 'Works as advertised, decent value.', 'expected': 'positive'},
]

def evaluate_classifier(test_set, classify_fn):
    correct = 0
    for example in test_set:
        result = classify_fn(example['text'])
        if result['sentiment'] == example['expected']:
            correct += 1
        else:
            print(f'WRONG: "{example["text"][:40]}" -> got {result["sentiment"]}, expected {example["expected"]}')
    accuracy = correct / len(test_set)
    print(f'Accuracy: {correct}/{len(test_set)} = {accuracy:.0%}')
    return accuracy

evaluate_classifier(labeled_test_set, classify_sentiment)

분류 프롬프트의 소수 예시

분류 프롬프트에 소수 예시를 추가하면 경계 사례와 미묘한 범주의 정확도가 향상됩니다. 서로 비슷한 범주의 차이를 보여 주는 예시를 2~3개 배치하세요:

few_shot_classifier = '''
Classify each customer message as: billing, technical, or general.

Examples:
  Input: "I was charged twice for this month." -> billing
  Input: "The app crashes when I open the dashboard." -> technical
  Input: "Do you have a mobile app?" -> general
  Input: "My invoice shows the wrong plan." -> billing
  Input: "I cannot log in, I get error 403." -> technical

Now classify:
Input: {message}
Return JSON: {"category": str, "confidence": "high|medium|low"}
'''

message = "My subscription was renewed but I cancelled last week."
prompt = few_shot_classifier.replace("{message}", message)
print(prompt)

간단 확인

기존에 학습된 분류기와 비교할 때 텍스트 분류에 LLM을 사용하는 가장 큰 장점은 무엇인가요?

분류기로서의 LLM — 핵심 요점

LLM 기반 분류는 강력하고 유연하며 빠르게 배포할 수 있습니다:

  • 미묘한 사례를 올바르게 처리할 수 있도록 범주를 이름뿐 아니라 설명과 함께 정의하세요
  • 모든 분류 결과에 범주와 신뢰도를 포함한 JSON을 반환하세요
  • 일반적인 패턴: 감성(긍정/부정/중립), 의도, 주제, 긴급도
  • 다중 레이블 분류는 해당하는 모든 범주와 기본 레이블을 반환합니다
  • 일괄 분류는 효율성을 위해 하나의 API 호출로 여러 입력을 처리합니다
  • 모호한 입력을 명시적으로 처리하세요 — 기본 범주와 대안 및 판단 근거를 요청하세요
  • 운영 환경에 배포하기 전에 레이블이 지정된 검증 세트를 기준으로 정확도를 평가하세요

자주 묻는 질문

“텍스트 분류기로서의 LLM” 강의는 무료인가요?

네 — “텍스트 분류기로서의 LLM” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 AI Prompt Engineering 강의 전체를 잠금 해제할 수 있습니다. AI Prompt Engineering 강의에는 총 4개의 강의가 포함되어 있습니다.

“텍스트 분류기로서의 LLM”에서 뭘 배우나요?

감성, 의도, 주제 및 다중 레이블 분류에 프롬프트를 활용합니다. 브라우저에서 직접 실행하는 실습 코드로 AI Prompt Engineering을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

AI Prompt Engineering을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 AI Prompt Engineering은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.

“텍스트 분류기로서의 LLM” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 AI Prompt Engineering 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 AI Prompt Engineering 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

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