Transfer Learning
Transfer Learning
A technique that applies a pretrained model to a new task. Achieves high performance with little data and cost.
Transfer Learning
A technique that applies a pretrained model to a new task. Achieves high performance with little data and cost.
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.
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")
Take a mock interview on this topic โ WIA SOOM AI Interview ยท Start for free
Using a high LR during Fine-tuning destroys the pre-trained knowledge. Generally, use 1e-5 to 5e-5.
Using an English model for a Korean-language task degrades performance. Choose a model trained on data similar to the target domain.
Consider choosing a Pre-trained model suited to the domain, Gradual Unfreezing, and applying layer-wise differential LRs.