Zero-Shot Learning
Zero-Shot Learning
The ability to perform a new task without examples. An AI technique that generalizes using only pretrained knowledge.
Zero-Shot Learning
The ability to perform a new task without examples. An AI technique that generalizes using only pretrained knowledge.
Zero-Shot Learning refers to the ability of a model to perform a new task without examples or training data for that specific task. "Zero" means that there are 0 task-specific training examples, and the model solves a task it has never seen using only the general knowledge it acquired during pre-training.
This concept was first proposed in the computer vision field in 2013, and it originated from the problem of recognizing object classes that had never been seen before. Later, with the emergence of GPT-3 (2020), Zero-Shot capability in LLMs began to attract attention, and it was demonstrated that a variety of NLP tasks can be performed with prompts alone.
The core principle of Zero-Shot is knowledge transfer in a semantic space. While training on large-scale data, the model acquires relationships between concepts and language patterns. When given a new task, it uses this general knowledge to understand the meaning of the task and generate an appropriate output. In an LLM, sentiment analysis becomes possible with just an instruction such as "Classify the sentiment of this text."
In practice, Zero-Shot Learning is useful when labeled data is scarce or when rapid prototyping is needed. Its accuracy may be lower than that of Few-Shot (a small number of examples) or Fine-tuning, but it has the advantage of being usable immediately without data collection/labeling costs. In particular, with the latest LLMs such as GPT-4 and Claude, Zero-Shot performance has improved significantly and has reached a practical level for many tasks.
# Zero-Shot Learning 예제: 다양한 NLP 작업
from openai import OpenAI
client = OpenAI(api_key="your-api-key")
# Zero-Shot 감정 분석 (예시 없이 작업 수행)
def zero_shot_sentiment(text: str) -> str:
response = client.chat.completions.create(
model="gpt-4",
messages=[
{"role": "system", "content": "당신은 텍스트 감정 분석 전문가입니다."},
{"role": "user", "content": f"""
다음 텍스트의 감정을 분석하세요.
긍정(positive), 부정(negative), 중립(neutral) 중 하나로 답하세요.
텍스트: {text}
감정:"""}
],
max_tokens=10,
temperature=0
)
return response.choices[0].message.content.strip()
# Zero-Shot 텍스트 분류 (커스텀 카테고리)
def zero_shot_classification(text: str, categories: list) -> str:
category_str = ", ".join(categories)
response = client.chat.completions.create(
model="gpt-4",
messages=[
{"role": "user", "content": f"""
다음 텍스트를 아래 카테고리 중 가장 적합한 것으로 분류하세요.
카테고리: {category_str}
텍스트: {text}
선택한 카테고리 하나만 출력하세요:"""}
],
max_tokens=20,
temperature=0
)
return response.choices[0].message.content.strip()
# Hugging Face 모델을 활용한 Zero-Shot Classification
from transformers import pipeline
def zero_shot_with_huggingface(text: str, candidate_labels: list) -> dict:
"""
Hugging Face의 zero-shot-classification 파이프라인 사용
모델: facebook/bart-large-mnli (NLI 기반 분류)
"""
classifier = pipeline(
"zero-shot-classification",
model="facebook/bart-large-mnli"
)
result = classifier(
text,
candidate_labels=candidate_labels,
multi_label=False # 단일 레이블 분류
)
return {
"text": text,
"predicted_label": result["labels"][0],
"confidence": result["scores"][0],
"all_scores": dict(zip(result["labels"], result["scores"]))
}
# Zero-Shot vs Few-Shot 비교 함수
def compare_zero_few_shot(text: str, examples: list = None) -> dict:
"""
Zero-Shot과 Few-Shot 결과를 비교합니다.
examples: [{"text": "...", "label": "..."}] 형식의 예시 리스트
"""
# Zero-Shot
zero_shot_result = zero_shot_sentiment(text)
# Few-Shot (예시가 있는 경우)
if examples:
example_str = "\n".join([
f"텍스트: {e['text']}\n감정: {e['label']}"
for e in examples
])
response = client.chat.completions.create(
model="gpt-4",
messages=[
{"role": "user", "content": f"""
텍스트의 감정을 분석하세요.
예시:
{example_str}
텍스트: {text}
감정:"""}
],
max_tokens=10,
temperature=0
)
few_shot_result = response.choices[0].message.content.strip()
else:
few_shot_result = None
return {
"text": text,
"zero_shot": zero_shot_result,
"few_shot": few_shot_result,
"examples_count": len(examples) if examples else 0
}
# 실행 예제
if __name__ == "__main__":
# Zero-Shot 감정 분석
result = zero_shot_sentiment("이 제품 정말 마음에 들어요! 배송도 빨랐어요.")
print(f"감정: {result}") # positive
# Zero-Shot 커스텀 분류
categories = ["기술", "스포츠", "정치", "연예", "경제"]
text = "애플이 새로운 아이폰 발표회를 열었습니다."
result = zero_shot_classification(text, categories)
print(f"분류: {result}") # 기술
# Hugging Face Zero-Shot
result = zero_shot_with_huggingface(
"The stock market reached an all-time high today.",
["finance", "sports", "technology", "politics"]
)
print(f"HF 분류: {result['predicted_label']} ({result['confidence']:.2%})")
"We need to build a new review category classification model, but we don't have any labeled data." - "Let's start with Zero-Shot for now. We can give GPT-4 or Claude the list of categories and try classifying with just a prompt. If an accuracy of around 85% is enough, we can use it in production right away, and if it falls short, we can collect the misclassified cases and improve with Few-Shot or Fine-tuning."
"Please explain the difference between Zero-Shot and Few-Shot Learning." - "Zero-Shot performs the task with only a prompt instruction and no task-specific examples, while Few-Shot includes a few examples in the prompt to show the pattern. Few-Shot generally has higher accuracy, but the number of prompt tokens increases, which raises costs. You choose based on task difficulty and budget. In fact, at the level of GPT-4, Zero-Shot also shows sufficiently good performance on many basic tasks."
"How does the Hugging Face zero-shot-classification pipeline work?" - "It uses an NLI (Natural Language Inference) model. It converts the input text and each label into premise-hypothesis pairs and judges whether something like 'This text is about sports' is true. facebook/bart-large-mnli is a representative example, but it is optimized for English, so for Korean it is better to use a multilingual model such as mDeBERTa."
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free
In domain-specific tasks (legal document analysis, medical code classification, etc.), Zero-Shot accuracy may be only 50–60%. If high accuracy is required, consider Few-Shot or Fine-tuning.
Zero-Shot performance depends heavily on prompt quality. Specific instructions such as "Select the most appropriate one from the following categories: A, B, C" improve accuracy more than "Classify this."
Quickly build a prototype with Zero-Shot and analyze the actual error cases. If there are patterns that are frequently wrong, a gradual approach is effective: add those examples to the Few-Shot prompt, or switch to Fine-tuning once enough data has accumulated.