🤖 AI/ML

Transfer Learning

Transfer Learning

A technique that applies a pretrained model to a new task. High performance with little data. The basis of fine-tuning.

📖 Detailed Explanation

Transfer Learning is a machine learning technique that applies knowledge learned in one domain to solving problems in another related domain. By reusing the weights of a model pre-trained on a large-scale dataset for a new task, high performance can be achieved even with little data. As a core paradigm of modern Deep Learning, nearly all of the latest AI models, including GPT, BERT, and ResNet, are based on transfer learning.

The core principle of transfer learning is the generality of low-level features. The early layers of image models learn general features such as edges and textures, while language models learn grammar and semantic structure. This general knowledge is also useful for new tasks, and models are adapted to a specific task by replacing only the final layer or by fine-tuning the entire model.

Transfer learning has three main approaches: (1) Feature Extraction - freeze the pre-trained model and train only the final classification layer, (2) Fine-tuning - retrain the entire model at a low learning rate, using the pre-trained weights as initial values, (3) Domain Adaptation - a technique that reduces the distribution difference between the source domain and the target domain. Feature Extraction is more effective when data is scarce, and Fine-tuning is more effective when data is sufficient.

As of 2025, transfer learning is the basic strategy of the Foundation Model era. LLMs such as GPT-4, Claude, and Gemini are pre-trained on trillions of tokens and then fine-tuned for specific domains. As efficient fine-tuning techniques such as LoRA and QLoRA have advanced, even small organizations can now adapt large models to their own data. It reduces training costs by more than 90% while delivering superior performance compared to training from scratch.

💻 Code Example

Transfer learning with PyTorch (ResNet → custom classifier):

import torch
import torch.nn as nn
from torchvision import models
from transformers import AutoModel, AutoTokenizer

# 방법 1: 이미지 분류 - ResNet 전이 학습
def create_transfer_model(num_classes, freeze_backbone=True):
    """
    ResNet50 사전학습 모델을 커스텀 분류기로 전이
    """
    # 사전학습된 가중치 로드
    model = models.resnet50(weights='IMAGENET1K_V2')

    # Feature Extraction: backbone 동결
    if freeze_backbone:
        for param in model.parameters():
            param.requires_grad = False

    # 최종 분류 레이어 교체
    num_features = model.fc.in_features
    model.fc = nn.Sequential(
        nn.Dropout(0.3),
        nn.Linear(num_features, 256),
        nn.ReLU(),
        nn.Linear(256, num_classes)
    )
    return model

# 방법 2: NLP - BERT Fine-tuning
class BertClassifier(nn.Module):
    def __init__(self, num_classes):
        super().__init__()
        self.bert = AutoModel.from_pretrained('bert-base-multilingual-cased')
        self.classifier = nn.Linear(768, num_classes)

    def forward(self, input_ids, attention_mask):
        outputs = self.bert(input_ids, attention_mask=attention_mask)
        pooled = outputs.last_hidden_state[:, 0]  # [CLS] 토큰
        return self.classifier(pooled)

# 방법 3: LoRA 효율적 파인튜닝 (2024년 표준)
from peft import LoraConfig, get_peft_model

def apply_lora_finetuning(model):
    """대형 LLM을 0.1%의 파라미터만으로 파인튜닝"""
    lora_config = LoraConfig(
        r=8,              # Low-rank 차원
        lora_alpha=16,    # 스케일링 팩터
        target_modules=["q_proj", "v_proj"],
        lora_dropout=0.1
    )
    return get_peft_model(model, lora_config)

📊 Performance & Cost

Training Method Required Data Training Time GPU Cost (Example)
Scratch Training 1M+ samples 100% (baseline) $10,000+
Feature Extraction 1,000-10,000 samples 1-5% $10-50
Full Fine-tuning 10,000-100,000 samples 5-15% $50-500
LoRA Fine-tuning 1,000-10,000 samples 1-3% $10-100
Prompt Tuning 100-1,000 samples 0.1-1% $1-10

※ Costs are estimates based on cloud GPUs (A100), and vary depending on model size and data

🗣️ Say It Like This in Practice

💬 In Project Planning
"We only have 5,000 data samples, so training from scratch is not feasible. If we take BERT-base and fine-tune it, we can achieve over 90% accuracy within 2 weeks."
💬 In Model Review
"We applied LoRA to LLM fine-tuning. By training only 0.1% of all parameters, we reduced memory usage by 80%, and training a 7B model became possible even with a single A100."
💬 In an Interview
"Transfer learning is a technique that transfers knowledge from the source domain to the target domain. To prevent Negative Transfer, you need to evaluate domain similarity and choose an appropriate learning rate and freezing strategy."

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

⚠️ Common Mistakes & Cautions

❌
Fine-tuning with a high learning rate

If the pre-trained weights change abruptly, "catastrophic forgetting" occurs. When fine-tuning, set the learning rate to 1/10 or less of that used in pre-training.

❌
Ignoring domain mismatch

Applying an ImageNet model directly to medical images degrades performance. Consider a domain-specific pre-trained model (e.g., MedCLIP) first.

❌
Missing license check

Some pre-trained models have restrictions on commercial use. Be sure to check the license terms of Llama 2, Mistral, and others.

✅
The right approach

If data is scarce, start with Feature Extraction; if it is sufficient, fine-tune with gradual unfreezing. Always monitor overfitting with a validation set.

🔗 Related Terms

📚 Learn More