๐Ÿค– AI/ML

Transfer Learning

Transfer Learning

A technique that applies a pretrained model to a new task. Achieves high performance with little data and cost.

๐Ÿ“– Detailed Explanation

Transfer Learning is a technique that applies knowledge learned in one domain to another domain or task. By taking the weights of a model pre-trained (Pre-training) on a large-scale dataset and fine-tuning (Fine-tuning) it for a new task, high performance can be achieved with less data and lower computational cost.

The concept of Transfer Learning has been studied since the 1990s, but it began to attract serious attention after AlexNet showed groundbreaking performance on ImageNet in 2012. Later, with the emergence of BERT and GPT in NLP in 2018, the "Pre-train then Fine-tune" paradigm became the standard in AI development.

Technically, Transfer Learning proceeds by freezing the lower layers of the model (general feature extraction) and training only the upper layers (task-specific features). For example, a CNN trained on ImageNet already knows general-purpose features such as edges and textures in images, so it adapts quickly to new tasks such as medical image classification.

In practice, Transfer Learning is essential when data is scarce or training costs are limited. By using the thousands of pre-trained models available on Hugging Face, you can customize a GPT-4-level model for a specific domain without incurring millions of dollars in training costs.

๐Ÿ’ป Code Example

This is an example of BERT Transfer Learning using Hugging Face Transformers.

from transformers import (
    AutoTokenizer,
    AutoModelForSequenceClassification,
    TrainingArguments,
    Trainer
)
from datasets import load_dataset
import numpy as np
from sklearn.metrics import accuracy_score

# 1. ์‚ฌ์ „ ํ•™์Šต๋œ ๋ชจ๋ธ๊ณผ ํ† ํฌ๋‚˜์ด์ € ๋กœ๋“œ
model_name = "klue/bert-base"
tokenizer = AutoTokenizer.from_pretrained(model_name)

# ๋ถ„๋ฅ˜ ์ž‘์—…์„ ์œ„ํ•œ ํ—ค๋“œ ์ถ”๊ฐ€ (2๊ฐœ ํด๋ž˜์Šค: ๊ธ์ •/๋ถ€์ •)
model = AutoModelForSequenceClassification.from_pretrained(
    model_name,
    num_labels=2
)

# 2. ํ•˜์œ„ ๋ ˆ์ด์–ด ๋™๊ฒฐ (์„ ํƒ์ )
for param in model.bert.embeddings.parameters():
    param.requires_grad = False
for layer in model.bert.encoder.layer[:6]:  # ํ•˜์œ„ 6๊ฐœ ๋ ˆ์ด์–ด ๋™๊ฒฐ
    for param in layer.parameters():
        param.requires_grad = False

# 3. ๋ฐ์ดํ„ฐ์…‹ ์ค€๋น„ (ํ•œ๊ตญ์–ด ๊ฐ์„ฑ ๋ถ„์„)
dataset = load_dataset("nsmc")

def tokenize_function(examples):
    return tokenizer(
        examples["document"],
        padding="max_length",
        truncation=True,
        max_length=128
    )

tokenized_datasets = dataset.map(tokenize_function, batched=True)

# 4. ํ›ˆ๋ จ ์„ค์ •
training_args = TrainingArguments(
    output_dir="./results",
    num_train_epochs=3,
    per_device_train_batch_size=16,
    per_device_eval_batch_size=64,
    learning_rate=2e-5,  # Fine-tuning์€ ๋‚ฎ์€ LR ์‚ฌ์šฉ
    warmup_steps=500,
    weight_decay=0.01,
    evaluation_strategy="epoch",
    save_strategy="epoch",
    load_best_model_at_end=True,
)

def compute_metrics(eval_pred):
    predictions, labels = eval_pred
    predictions = np.argmax(predictions, axis=1)
    return {"accuracy": accuracy_score(labels, predictions)}

# 5. Trainer๋กœ Fine-tuning
trainer = Trainer(
    model=model,
    args=training_args,
    train_dataset=tokenized_datasets["train"],
    eval_dataset=tokenized_datasets["test"],
    compute_metrics=compute_metrics,
)

trainer.train()
print("Transfer Learning ์™„๋ฃŒ! ๋ชจ๋ธ ์ €์žฅ ์ค‘...")
trainer.save_model("./my-sentiment-model")

๐Ÿ—ฃ๏ธ Say It Like This in Practice

๐Ÿ’ฌ In a Meeting
"We only have 5,000 medical text records, so we're planning to use BERT with Transfer Learning. We expect accuracy to be more than 15% higher than training from scratch."
๐Ÿ’ฌ In an Interview
"We used Transfer Learning when building a domain-specific model. We fine-tuned KoELECTRA for financial document classification and achieved an F1 score of 92%."
๐Ÿ’ฌ In a Technical Discussion
"If the difference between the source domain and the target domain is large, Negative Transfer can occur. Consider using Domain Adaptation techniques as well."

Take a mock interview on this topic โ†’ WIA SOOM AI Interview ยท Start for free

โš ๏ธ Common Mistakes & Cautions

โŒ

Learning Rate is too high

Using a high LR during Fine-tuning destroys the pre-trained knowledge. Generally, use 1e-5 to 5e-5.

โŒ

Choosing an unrelated pre-trained model

Using an English model for a Korean-language task degrades performance. Choose a model trained on data similar to the target domain.

โœ…

The right way

Consider choosing a Pre-trained model suited to the domain, Gradual Unfreezing, and applying layer-wise differential LRs.

๐Ÿ”— Related Terms

๐Ÿ“š Learn More