การปรับแต่ง BertForSequenceClassification
ผู้เรียนจะโหลดจุดตรวจสอบ BERT ที่ฝึกไว้ล่วงหน้า เพิ่มส่วนหัวการจำแนก สร้าง PyTorch DataLoader และปรับแต่งเป็นเวลาสองยุคบนชุดข้อมูล IMDB
การปรับแต่ง BertForSequenceClassification เป็นบทเรียน Machine Learning Academy ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Machine Learning Academy และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Machine Learning Academy มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
What Is Fine-Tuning?
Fine-tuning takes a pre-trained model that already understands language structure and adapts it to a specific task with a small labelled dataset. BERT pre-trained on 3.3 billion words already knows grammar, semantics, and world knowledge. Fine-tuning adds a task-specific head (e.g., a classification layer) and trains the entire model end-to-end on your labelled data for a few epochs, achieving state-of-the-art results with far less data and compute than training from scratch.
BertForSequenceClassification Overview
BertForSequenceClassification is a BERT model with a linear classification head on top of the [CLS] token's final hidden state. It is the standard Hugging Face class for sentiment analysis, topic classification, and any task that assigns a single label to an entire text. The head is initialised randomly and trained alongside the BERT backbone during fine-tuning.
from transformers import BertForSequenceClassification
import torch
# 2 classes: negative (0) and positive (1)
model = BertForSequenceClassification.from_pretrained(
'bert-base-uncased',
num_labels=2
)
print(model.config.num_labels) # 2
print(model.classifier) # Linear(in=768, out=2)Loading the IMDB Dataset
The IMDB dataset contains 50,000 movie reviews labelled positive (1) or negative (0). We use the Hugging Face datasets library to download and split it. The dataset object behaves like a dictionary of lists and can be mapped over with a tokenization function. We use a 25k train / 25k test split provided by the original dataset authors.
from datasets import load_dataset
from transformers import BertTokenizer
dataset = load_dataset('imdb')
print(dataset) # DatasetDict with train/test splits
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
def tokenize_fn(examples):
return tokenizer(
examples['text'],
truncation=True,
padding='max_length',
max_length=256
)
tokenized = dataset.map(tokenize_fn, batched=True)
tokenized.set_format('torch', columns=['input_ids', 'attention_mask', 'label'])Creating PyTorch DataLoaders
After tokenisation, wrap the Hugging Face dataset in PyTorch DataLoader objects. The batch_size controls how many examples the model processes per forward pass; 16 or 32 is typical for BERT given GPU memory constraints. Shuffle the training set each epoch so the model does not overfit to example order, but keep the validation set fixed for reproducible evaluation.
from torch.utils.data import DataLoader
train_dataset = tokenized['train'].select(range(2000)) # small subset for demo
test_dataset = tokenized['test'].select(range(500))
train_loader = DataLoader(train_dataset, batch_size=16, shuffle=True)
test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)
print('Train batches:', len(train_loader))
print('Test batches:', len(test_loader))Setting Up the Optimizer
Fine-tuning BERT uses the AdamW optimizer with a small learning rate (typically 2e-5 to 5e-5). Using a large learning rate destroys the pre-trained representations (catastrophic forgetting). Weight decay (L2 regularisation) is applied to non-bias parameters to reduce overfitting. Hugging Face's get_linear_schedule_with_warmup is commonly used to warm up the LR over the first 10% of steps then decay linearly.
from torch.optim import AdamW
from transformers import get_linear_schedule_with_warmup
optimizer = AdamW(model.parameters(), lr=2e-5, weight_decay=0.01)
num_epochs = 2
num_steps = len(train_loader) * num_epochs
warmup_steps = int(0.1 * num_steps)
scheduler = get_linear_schedule_with_warmup(
optimizer,
num_warmup_steps=warmup_steps,
num_training_steps=num_steps
)The Fine-Tuning Training Loop
The PyTorch training loop for fine-tuning BERT follows the standard pattern: iterate over batches, compute the forward pass, extract the loss from the model output (BertForSequenceClassification returns loss automatically when labels are passed), call loss.backward(), clip gradients to prevent explosion, and step the optimizer and scheduler. Training BERT for 2 epochs on IMDB typically yields ~92% accuracy.
import torch
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model = model.to(device)
for epoch in range(2):
model.train()
total_loss = 0
for batch in train_loader:
optimizer.zero_grad()
input_ids = batch['input_ids'].to(device)
attention_mask = batch['attention_mask'].to(device)
labels = batch['label'].to(device)
outputs = model(input_ids=input_ids,
attention_mask=attention_mask,
labels=labels)
loss = outputs.loss
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
optimizer.step()
scheduler.step()
total_loss += loss.item()
print(f'Epoch {epoch+1} loss: {total_loss/len(train_loader):.4f}')Evaluating on the Validation Set
During evaluation, call model.eval() to disable dropout and use torch.no_grad() to skip gradient computation, saving memory and speeding up inference. Extract logits from the model output (raw scores before softmax), apply argmax to get predicted class indices, and compare against ground-truth labels to compute accuracy.
import torch
from sklearn.metrics import accuracy_score
model.eval()
all_preds, all_labels = [], []
with torch.no_grad():
for batch in test_loader:
input_ids = batch['input_ids'].to(device)
attention_mask = batch['attention_mask'].to(device)
labels = batch['label'].to(device)
outputs = model(input_ids=input_ids,
attention_mask=attention_mask)
preds = torch.argmax(outputs.logits, dim=1)
all_preds.extend(preds.cpu().numpy())
all_labels.extend(labels.cpu().numpy())
print('Accuracy:', accuracy_score(all_labels, all_preds))Saving the Fine-Tuned Model
After fine-tuning, save the model and tokenizer together so they can be reloaded for inference without re-training. model.save_pretrained(path) saves the model weights and config; tokenizer.save_pretrained(path) saves the vocabulary and tokenization settings. Reload with from_pretrained(path) in any new Python session.
import os
save_dir = './bert_imdb_finetuned'
os.makedirs(save_dir, exist_ok=True)
model.save_pretrained(save_dir)
tokenizer.save_pretrained(save_dir)
print('Model saved to', save_dir)
# Reload in a new session:
# from transformers import BertForSequenceClassification, BertTokenizer
# model = BertForSequenceClassification.from_pretrained(save_dir)
# tokenizer = BertTokenizer.from_pretrained(save_dir)Using the Trainer API
Hugging Face's Trainer class encapsulates the training loop, evaluation, checkpointing, and logging in a single high-level API. Define a TrainingArguments object with learning rate, batch size, and number of epochs, then call trainer.train(). The Trainer handles gradient clipping, LR scheduling, and mixed-precision training automatically, reducing boilerplate significantly.
from transformers import Trainer, TrainingArguments
import numpy as np
from sklearn.metrics import accuracy_score
def compute_metrics(eval_pred):
logits, labels = eval_pred
preds = np.argmax(logits, axis=1)
return {'accuracy': accuracy_score(labels, preds)}
training_args = TrainingArguments(
output_dir='./bert_trainer',
num_train_epochs=2,
per_device_train_batch_size=16,
per_device_eval_batch_size=32,
learning_rate=2e-5,
evaluation_strategy='epoch',
save_strategy='epoch',
load_best_model_at_end=True
)
trainer = Trainer(
model=model,
args=training_args,
train_dataset=train_dataset,
eval_dataset=test_dataset,
compute_metrics=compute_metrics
)
trainer.train()Monitoring Training with TensorBoard
Pass report_to='tensorboard' in TrainingArguments to log loss and metrics to TensorBoard automatically. Launch TensorBoard with tensorboard --logdir ./bert_trainer/runs in a terminal to view real-time loss curves, learning rate schedules, and evaluation metrics. Monitoring training loss vs validation loss helps you detect overfitting early and stop training at the right epoch.
from transformers import TrainingArguments
training_args = TrainingArguments(
output_dir='./bert_trainer',
num_train_epochs=3,
per_device_train_batch_size=16,
learning_rate=2e-5,
evaluation_strategy='steps',
eval_steps=100,
logging_steps=50,
report_to='tensorboard', # enable TensorBoard logging
logging_dir='./bert_trainer/runs'
)
# Then: tensorboard --logdir ./bert_trainer/runsChoosing How Many Layers to Freeze
Sometimes the dataset is too small to fine-tune all 12 BERT layers without overfitting. A common strategy is to freeze the lower layers (which learn general linguistic features) and only update the upper layers (which learn task-specific features). Freeze by setting requires_grad=False on selected parameter groups. Monitor validation accuracy to choose the optimal freezing depth for your dataset size.
from transformers import BertForSequenceClassification
model = BertForSequenceClassification.from_pretrained('bert-base-uncased', num_labels=2)
# Freeze embedding layer and first 6 encoder layers
for name, param in model.named_parameters():
if 'embeddings' in name or 'encoder.layer.0' in name or \
'encoder.layer.1' in name or 'encoder.layer.2' in name:
param.requires_grad = False
# Count trainable parameters
trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)
print(f'Trainable parameters: {trainable:,}')Quick Check
Test your understanding of Machine Learning with Python concepts from this lesson.
Lesson Recap
In this lesson you learned: BertForSequenceClassification adds a linear head on [CLS] for classification tasks, fine-tuning uses AdamW with a very small learning rate to avoid catastrophic forgetting, and the Hugging Face Trainer API simplifies the training loop with built-in evaluation and checkpointing. Next up we look at how to extract predictions from logits and evaluate the fine-tuned model with accuracy and F1.
คำถามที่พบบ่อย
บทเรียน “การปรับแต่ง BertForSequenceClassification” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การปรับแต่ง BertForSequenceClassification” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Machine Learning Academy ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Machine Learning Academy มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การปรับแต่ง BertForSequenceClassification”
ผู้เรียนจะโหลดจุดตรวจสอบ BERT ที่ฝึกไว้ล่วงหน้า เพิ่มส่วนหัวการจำแนก สร้าง PyTorch DataLoader และปรับแต่งเป็นเวลาสองยุคบนชุดข้อมูล IMDB คุณปฏิบัติ Machine Learning Academy ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Machine Learning Academy หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน Machine Learning Academy บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน
บทเรียน “การปรับแต่ง BertForSequenceClassification” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน Machine Learning Academy นี้ได้ไหม
ได้ บทเรียน Machine Learning Academy ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- สถาปัตยกรรม Transformer: ความใส่ใจ โทเค็น และบริบท
- ตัวแยกโทเค็น Hugging Face: การเข้ารหัสข้อความสำหรับ BERT
- การปรับแต่ง BertForSequenceClassification
- การประเมินและการอนุมาน: จากลอจิตสู่ป้ายกำกับที่ทำนาย