🤖 AI/ML

Few-shot Learning

Few-Shot Learning

A technique for learning a new task from only a few examples. A core in-context learning capability of LLMs.

📖 Detailed Explanation

Few-shot Learning is a learning technique that performs a new task with only a small number of examples (usually 1-5). In LLMs, a few input-output examples are provided in the prompt so that the model identifies the pattern and responds in the same format. It is divided into Zero-shot (no examples), One-shot (1 example), and Few-shot (2-5 examples).

The concept of Few-shot Learning was popularized in the 2020 GPT-3 paper "Language Models are Few-Shot Learners". The paper showed that a 175B-parameter model can perform a variety of NLP tasks using only examples in the prompt, without fine-tuning. This is called In-Context Learning (ICL), and it is one of the emergent abilities of LLMs.

The core principle of Few-shot Learning is that the model infers the task pattern from the examples in the prompt. The model's weights do not change; the examples in the context condition the output distribution. The format, order, and diversity of the examples have a large effect on performance. According to recent research, there are cases where the format matters more than the labels of the examples.

In practice, Few-shot Learning is useful for rapid prototyping and in situations where data is scarce. Whereas fine-tuning requires thousands of examples, Few-shot needs only 3-5. However, for tasks requiring complex reasoning, it is used in combination with Chain-of-Thought prompting. In production, the Dynamic Few-shot technique, which selects examples dynamically, improves performance.

💻 Code Example

from openai import OpenAI

client = OpenAI()

# 1. Zero-shot: 예시 없이 직접 질문
def zero_shot_sentiment(text):
    response = client.chat.completions.create(
        model="gpt-4",
        messages=[
            {"role": "system", "content": "텍스트의 감성을 '긍정', '부정', '중립' 중 하나로 분류하세요."},
            {"role": "user", "content": text}
        ]
    )
    return response.choices[0].message.content

# 2. Few-shot: 예시와 함께 질문
def few_shot_sentiment(text):
    few_shot_examples = """
다음은 감성 분류 예시입니다:

텍스트: 이 제품 정말 최고예요! 강력 추천합니다.
감성: 긍정

텍스트: 배송이 너무 늦고 제품 상태도 별로였습니다.
감성: 부정

텍스트: 평범한 제품이네요. 가격 대비 적당합니다.
감성: 중립

텍스트: {text}
감성:"""

    response = client.chat.completions.create(
        model="gpt-4",
        messages=[
            {"role": "user", "content": few_shot_examples.format(text=text)}
        ],
        max_tokens=10
    )
    return response.choices[0].message.content.strip()

# 3. Chain-of-Thought + Few-shot (복잡한 추론)
def few_shot_math_reasoning(problem):
    prompt = """
문제를 단계별로 풀어주세요.

문제: 사과 5개가 있는데 3개를 먹고, 다음날 2개를 더 샀습니다. 몇 개가 있나요?
풀이:
1. 처음 사과: 5개
2. 3개를 먹음: 5 - 3 = 2개
3. 2개를 더 삼: 2 + 2 = 4개
답: 4개

문제: 철수는 1000원이 있습니다. 300원짜리 과자 2개를 사면 얼마가 남나요?
풀이:
1. 처음 금액: 1000원
2. 과자 2개 가격: 300 * 2 = 600원
3. 남은 금액: 1000 - 600 = 400원
답: 400원

문제: {problem}
풀이:"""

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

# 4. Dynamic Few-shot: 쿼리와 유사한 예시 자동 선택
from sentence_transformers import SentenceTransformer
import numpy as np

class DynamicFewShot:
    def __init__(self, examples):
        self.examples = examples
        self.encoder = SentenceTransformer('all-MiniLM-L6-v2')
        self.example_embeddings = self.encoder.encode(
            [ex['input'] for ex in examples]
        )

    def get_similar_examples(self, query, k=3):
        query_embedding = self.encoder.encode([query])[0]
        similarities = np.dot(self.example_embeddings, query_embedding)
        top_indices = np.argsort(similarities)[-k:][::-1]
        return [self.examples[i] for i in top_indices]

    def generate(self, query):
        similar_examples = self.get_similar_examples(query)
        prompt = "예시:\n"
        for ex in similar_examples:
            prompt += f"입력: {ex['input']}\n출력: {ex['output']}\n\n"
        prompt += f"입력: {query}\n출력:"
        return prompt

# 사용 예시
print(few_shot_sentiment("이번 업데이트 정말 마음에 들어요!"))
print(few_shot_math_reasoning("책 3권이 각각 2000원입니다. 10000원으로 몇 권 살 수 있나요?"))

🗣️ Say It Like This in Practice

In a prompt engineering meeting

"We're using Few-shot for automatic classification of customer inquiries, and accuracy rose by 8% with 5 examples compared to 3. However, token costs increased, so we're considering switching to Dynamic Few-shot for cost optimization. If we select only examples similar to the query, 3 should be enough."

During a discussion on LLM application development

"The model didn't understand our domain terminology well with Zero-shot, but switching to Few-shot fixed it. Since the examples clearly show the domain-specific terms and the output format, the model follows the pattern well. We don't need fine-tuning, so development is much faster."

In an ML engineer interview

"There are several hypotheses about why Few-shot Learning works, and the most plausible is that the examples condition the model's output format. Interestingly, performance doesn't always drop significantly even when the labels of the examples are randomly changed, so there are research findings that the format matters more than the labels."

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

⚠️ Common Mistakes & Cautions

1
The Effect of Example Order and Format

The order of Few-shot examples affects performance. In general, it is better to place easy examples first and difficult examples later. Also, keep the format of the examples (delimiters, line breaks, etc.) consistent. If the format is irregular, it is hard for the model to identify the pattern.

2
Context Length Limits

More examples are better, but models have context length limits. If you include many long examples, there is not enough room left for the actual query. Write examples concisely and include only the essentials. Even with GPT-4's 128K context, efficient example design is important.

3
Ensuring Example Diversity

Biased examples produce biased outputs. In classification tasks, if there are many examples of only a particular class, the output will be biased toward that class. Place examples evenly across each class, and include edge cases as well. Showing various forms of input helps generalization.

🔗 Related Terms

📚 Learn More