🤖 AI/ML

Zero-shot

Zero-shot

Performs a new task without examples. A prompt-based inference approach that leverages the generalization ability of LLMs.

📖 Detailed Explanation

Zero-shot is an approach in which an AI model performs a task using only a natural-language instruction, without any training examples for that specific task. The name comes from performing the task with "zero shots (examples)," and it contrasts with Few-shot (a few examples) and One-shot (one example).

The concept of Zero-shot was considered impossible in traditional machine learning, because a model needed training data for a given task in order to perform it. However, since GPT-3 (2020), large language models have learned sufficiently diverse task patterns during pre-training, and as a result they can understand and carry out instructions even without explicit examples.

The principle behind how Zero-shot works is based on the model's "emergent capabilities." In the course of learning from large text corpora, the model implicitly acquires the patterns of various tasks such as question answering, translation, and summarization. The fact that a model can perform translation from an instruction alone, such as "Translate the following sentence into Korean," is because similar patterns were included in its training data.

In practice, Zero-shot is useful for rapid prototyping, situations without labeled data, or when various tasks must be handled by a single model. However, accuracy can be lower on complex domain-specific tasks, so it is used in combination with Few-shot or Fine-tuning depending on the situation.

💻 Code Example

# Zero-shot 프롬프팅 비교 예제
from openai import OpenAI
from anthropic import Anthropic

# OpenAI Zero-shot
openai_client = OpenAI(api_key="your-openai-key")

def zero_shot_openai(task_description: str, input_text: str) -> str:
    """
    Zero-shot: 예시 없이 작업 설명만으로 수행
    """
    response = openai_client.chat.completions.create(
        model="gpt-4",
        messages=[
            {"role": "system", "content": task_description},
            {"role": "user", "content": input_text}
        ],
        temperature=0
    )
    return response.choices[0].message.content

# Claude Zero-shot
anthropic_client = Anthropic(api_key="your-anthropic-key")

def zero_shot_claude(task_description: str, input_text: str) -> str:
    """
    Claude에서의 Zero-shot 프롬프팅
    """
    message = anthropic_client.messages.create(
        model="claude-3-5-sonnet-20241022",
        max_tokens=1000,
        messages=[{
            "role": "user",
            "content": f"{task_description}\n\n입력: {input_text}\n\n출력:"
        }]
    )
    return message.content[0].text

# Zero-shot vs Few-shot 비교
def compare_approaches(text: str) -> dict:
    """
    동일한 작업에 대해 Zero-shot과 Few-shot 결과 비교
    """
    # Zero-shot: 지시만 제공
    zero_shot_prompt = """다음 텍스트가 긍정적(positive), 부정적(negative), 중립적(neutral) 중
어떤 감정인지 판단하세요. 감정 레이블만 출력하세요."""

    zero_result = zero_shot_openai(zero_shot_prompt, text)

    # Few-shot: 예시 포함
    few_shot_prompt = """다음 텍스트의 감정을 분류하세요.

예시 1:
텍스트: "이 영화 정말 재미있었어요!"
감정: positive

예시 2:
텍스트: "서비스가 너무 느려서 화가 났습니다."
감정: negative

예시 3:
텍스트: "오늘 날씨는 맑습니다."
감정: neutral

이제 아래 텍스트를 분류하세요:"""

    few_result = zero_shot_openai(few_shot_prompt, text)

    return {
        "text": text,
        "zero_shot": zero_result,
        "few_shot": few_result
    }

# Zero-shot Chain-of-Thought (CoT)
def zero_shot_cot(question: str) -> str:
    """
    Zero-shot CoT: "단계별로 생각해보세요" 추가로 추론 능력 향상
    """
    prompt = f"""{question}

단계별로 생각해보세요."""

    response = openai_client.chat.completions.create(
        model="gpt-4",
        messages=[{"role": "user", "content": prompt}],
        temperature=0
    )
    return response.choices[0].message.content

# 다양한 Zero-shot 작업 예제
def demonstrate_zero_shot_tasks():
    # 1. 번역 (Zero-shot)
    translation = zero_shot_openai(
        "한국어를 영어로 번역하세요.",
        "인공지능이 세상을 바꾸고 있습니다."
    )
    print(f"번역: {translation}")

    # 2. 요약 (Zero-shot)
    summary = zero_shot_openai(
        "다음 텍스트를 한 문장으로 요약하세요.",
        """
        기계학습은 컴퓨터가 명시적으로 프로그래밍되지 않아도
        데이터로부터 학습할 수 있게 하는 인공지능의 한 분야입니다.
        다양한 알고리즘을 사용하여 패턴을 인식하고 예측합니다.
        """
    )
    print(f"요약: {summary}")

    # 3. NER (Zero-shot)
    ner = zero_shot_openai(
        "텍스트에서 인명, 조직명, 장소명을 추출하세요. JSON 형식으로 출력하세요.",
        "이재용 삼성전자 회장이 서울에서 기자회견을 열었습니다."
    )
    print(f"NER: {ner}")

    # 4. 추론 with CoT (Zero-shot)
    reasoning = zero_shot_cot(
        "가게에 사과가 23개 있었습니다. 오전에 15개를 팔고, 오후에 12개를 더 받았습니다. 현재 사과는 몇 개인가요?"
    )
    print(f"추론: {reasoning}")

# 실행
if __name__ == "__main__":
    # 감정 분석 비교
    result = compare_approaches("배송이 생각보다 늦었지만 제품 품질은 만족스럽습니다.")
    print(f"Zero-shot 결과: {result['zero_shot']}")
    print(f"Few-shot 결과: {result['few_shot']}")

    # 다양한 작업 데모
    demonstrate_zero_shot_tasks()

🗣️ Say It Like This in Practice

💬 In a Meeting

"We want to automatically classify customer inquiries, but we have no training data." - "Let's start with Zero-shot for now. You just instruct GPT-4, 'Classify customer inquiries as refund/shipping/product inquiry/other.' If accuracy reaches about 80%, you can use it right away, and if it falls short, you can collect the misclassified cases and add them as Few-shot examples."

💬 In an Interview

"Please explain the difference between Zero-shot, One-shot, and Few-shot." - "The difference is the number of examples included in the prompt. Zero-shot includes 0 examples, just the instruction; One-shot includes 1; and Few-shot usually includes 3 to 5 examples. The more examples there are, the better the model picks up the pattern, but token costs increase and you may run into context length limits. In practice, you test with Zero-shot first and upgrade to Few-shot if needed."

💬 In a Technical Discussion

"What is Zero-shot CoT?" - "It stands for Chain-of-Thought, and it's a technique where you add a phrase like 'Think step by step' so that the model explicitly outputs its reasoning process. It came out of a 2022 paper, and accuracy goes up significantly on math problems and logical reasoning. You don't give any examples and only request the reasoning process, so it's still Zero-shot."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Common Mistakes & Cautions

❌
Providing Vague Instructions

You need to specify a concrete output format, such as "Classify as one of positive/negative/neutral," rather than "Analyze." Since Zero-shot has no examples, the clarity of the instruction is even more important.

❌
Applying Zero-shot to Every Task

Zero-shot accuracy is low for tasks that require domain expertise, such as medical diagnosis and legal document analysis. In such cases, Few-shot examples or Fine-tuning are essential.

✅
The Right Approach

Build an MVP quickly with Zero-shot and analyze the actual error patterns. If there are cases that are repeatedly wrong, adding them as Few-shot examples for gradual improvement is effective.

🔗 Related Terms

📚 Learn More