這段程式碼使用了 Hugging Face 的 Transformers 庫和 PyTorch 來進行文本分類任務,具體是使用 BERT 模型來進行中文情感分類。以下是對每個步驟及其輸出的詳細中文解釋:
1. 引入必要的庫
from transformers import BertTokenizer, BertModel
import torch
- transformers: 來自 Hugging Face 的庫,提供各種預訓練的語言模型,如 BERT。
- torch: PyTorch 庫,用於深度學習模型的構建和訓練。
2. 選擇和加載 BERT 模型及其分詞器
# 選擇模型,例如'bert-base-uncased'(英文),'bert-base-chinese'(中文)
model_name = 'bert-base-chinese'
# 加載分詞器
tokenizer = BertTokenizer.from_pretrained(model_name)
# 加載模型
model = BertModel.from_pretrained(model_name)
model.eval() # 設置為評估模式
- model_name: 選擇中文版的 BERT 模型。
- BertTokenizer: 用於將文本轉換為 BERT 模型所需的輸入格式(如 token IDs)。
- BertModel: 加載預訓練的 BERT 模型。
- model.eval(): 將模型設置為評估模式,這在不進行訓練時有助於禁用 dropout 等層。
3. 分詞和將文本轉換為模型輸入格式
# 示例文本
text = "今天天氣很好,我打算去公園散步。"
# 分詞並轉換為ID
inputs = tokenizer(text, return_tensors='pt')
# 查看分詞結果
print(inputs)
- text: 要處理的中文文本。
- tokenizer: 將文本轉換為模型可接受的 tensor 格式,包括
input_ids、token_type_ids 和 attention_mask。
- print(inputs): 輸出分詞結果,顯示各個 token 的 ID、類型 ID 和注意力掩碼。
輸出範例
{
'input_ids': tensor([[ 101, 791, 1921, 1921, 3706, 2523, 1962, 8024, 2769, 2802, 5050, 1343,
1062, 1754, 3141, 3635, 511, 102]]),
'token_type_ids': tensor([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]),
'attention_mask': tensor([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]])
}
- input_ids: 該文本中每個字的唯一標識符。
- token_type_ids: 用於區分句子對(在單句情況下,全為0)。
- attention_mask: 指示哪些 token 是有效的(1),哪些是 padding(0)。
4. 加載預訓練的 BERT 模型並獲取輸出
with torch.no_grad():
outputs = model(**inputs)
# outputs是包含多個層的信息,例如last_hidden_state和pooler_output
last_hidden_state = outputs.last_hidden_state # (batch_size, sequence_length, hidden_size)
pooler_output = outputs.pooler_output # (batch_size, hidden_size)
print("Last hidden state shape:", last_hidden_state.shape)
print("Pooler output shape:", pooler_output.shape)
- torch.no_grad(): 禁用梯度計算,節省內存和計算資源,因為這是前向傳播而非訓練。
- outputs: BERT 模型的輸出,包含多層信息。
- last_hidden_state: 最後一層的隱藏狀態,形狀為
(batch_size, sequence_length, hidden_size)。
- pooler_output: 通過池化層得到的輸出,通常用於分類任務,形狀為
(batch_size, hidden_size)。
- print: 輸出這兩個張量的形狀。
輸出範例
Last hidden state shape: torch.Size([1, 18, 768])
Pooler output shape: torch.Size([1, 768])
- last_hidden_state.shape: 表示批次大小為1,序列長度為18,隱藏層維度為768。
- pooler_output.shape: 表示批次大小為1,隱藏層維度為768。
5. 準備訓練數據
from sklearn.model_selection import train_test_split
from torch.utils.data import Dataset, DataLoader
# 示例數據
texts = ["我喜歡這本書", "這個產品很差", "服務態度很好", "質量不好"]
labels = [1, 0, 1, 0] # 1表示正面,0表示負面
# 分割數據集
train_texts, val_texts, train_labels, val_labels = train_test_split(texts, labels, test_size=0.2)
- texts: 樣本文本,包含正面和負面評論。
- labels: 樣本對應的標籤,1表示正面,0表示負面。
- train_test_split: 將數據分割為訓練集和驗證集,此處測試集佔20%。
6. 定義自訂數據集類
class TextDataset(Dataset):
def __init__(self, texts, labels, tokenizer, max_len=128):
self.texts = texts
self.labels = labels
self.tokenizer = tokenizer
self.max_len = max_len
def __len__(self):
return len(self.texts)
def __getitem__(self, idx):
text = self.texts[idx]
label = self.labels[idx]
encoding = self.tokenizer(
text,
add_special_tokens=True,
max_length=self.max_len,
padding='max_length',
truncation=True,
return_tensors='pt'
)
return {
'input_ids': encoding['input_ids'].flatten(),
'attention_mask': encoding['attention_mask'].flatten(),
'labels': torch.tensor(label, dtype=torch.long)
}
# 創建數據集對象
train_dataset = TextDataset(train_texts, train_labels, tokenizer)
val_dataset = TextDataset(val_texts, val_labels, tokenizer)
- TextDataset: 繼承自
torch.utils.data.Dataset,用於處理文本和標籤。
- init: 初始化數據、標籤、分詞器和最大長度。
- len: 返回數據集的大小。
- getitem: 獲取指定索引的樣本,將文本轉換為模型輸入格式,並返回
input_ids、attention_mask 和 labels。
- train_dataset 和 val_dataset: 分別為訓練集和驗證集數據集對象。
7. 創建數據加載器
batch_size = 8
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
val_loader = DataLoader(val_dataset, batch_size=batch_size)
- batch_size: 每個批次處理的樣本數量,此處設為8。
- DataLoader: 用於批量加載數據,
shuffle=True 表示對訓練數據進行隨機打亂。
8. 定義分類模型
import torch.nn as nn
import torch.optim as optim
class BertClassifier(nn.Module):
def __init__(self, bert_model, num_classes):
super(BertClassifier, self).__init__()
self.bert = bert_model
self.dropout = nn.Dropout(p=0.3)
self.classifier = nn.Linear(self.bert.config.hidden_size, num_classes)
def forward(self, input_ids, attention_mask):
outputs = self.bert(
input_ids=input_ids,
attention_mask=attention_mask
)
pooled_output = outputs.pooler_output
dropout_output = self.dropout(pooled_output)
logits = self.classifier(dropout_output)
return logits
# 初始化模型
num_classes = 2
model = BertClassifier(model, num_classes)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model = model.to(device)
- BertClassifier: 自訂的分類模型,包含以下部分:
- self.bert: 引入預訓練的 BERT 模型。
- self.dropout: Dropout 層,用於防止過擬合,設置掉落概率為0.3。
- self.classifier: 全連接層,將 BERT 的隱藏層輸出轉換為分類標籤的 logits(此處有2個類別)。
- forward: 前向傳播過程,輸入
input_ids 和 attention_mask,經過 BERT、Dropout 和分類層,輸出 logits。
- device: 檢查是否有 GPU 可用,若有則使用 GPU,加快運算速度。
- model.to(device): 將模型移動到指定設備(GPU 或 CPU)。
9. 定義優化器和損失函數
optimizer = optim.AdamW(model.parameters(), lr=2e-5)
criterion = nn.CrossEntropyLoss()
- optimizer: 使用 AdamW 優化器,學習率設為 2e-5,適合微調 BERT 等預訓練模型。
- criterion: 損失函數使用交叉熵損失,適用於多分類問題。
10. 定義訓練函數
def train_epoch(model, data_loader, optimizer, criterion, device):
model.train()
total_loss = 0
correct_predictions = 0
for batch in data_loader:
input_ids = batch['input_ids'].to(device)
attention_mask = batch['attention_mask'].to(device)
labels = batch['labels'].to(device)
optimizer.zero_grad()
outputs = model(input_ids, attention_mask)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
total_loss += loss.item()
_, preds = torch.max(outputs, dim=1)
correct_predictions += torch.sum(preds == labels)
avg_loss = total_loss / len(data_loader)
accuracy = correct_predictions.double() / len(data_loader.dataset)
return avg_loss, accuracy
- model.train(): 設定模型為訓練模式,啟用 dropout 等訓練特有的層。
- total_loss 和 correct_predictions: 用於累計損失和正確預測數量。
- for batch in data_loader: 遍歷每個批次的數據。
- 將
input_ids、attention_mask 和 labels 移動到設備(GPU 或 CPU)。
- optimizer.zero_grad(): 清除先前的梯度。
- outputs = model(...): 前向傳播,計算 logits。
- loss = criterion(outputs, labels): 計算損失。
- loss.backward(): 反向傳播,計算梯度。
- optimizer.step(): 更新模型參數。
- total_loss += loss.item(): 累加損失。
- _, preds = torch.max(outputs, dim=1): 獲取預測標籤。
- correct_predictions += torch.sum(preds == labels): 累加正確預測的數量。
- avg_loss: 計算平均損失。
- accuracy: 計算精度。
- 返回 平均損失和精度。
11. 執行訓練迴圈
# 簡單訓練迴圈
epochs = 3
for epoch in range(epochs):
train_loss, train_acc = train_epoch(model, train_loader, optimizer, criterion, device)
print(f"Epoch {epoch+1}/{epochs}")
print(f"Train loss: {train_loss:.4f}, Train accuracy: {train_acc:.4f}")
- epochs = 3: 設定訓練的總迭代輪數為3。
- for epoch in range(epochs): 遍歷每個訓練輪次。
- 調用
train_epoch 函數進行一個訓練輪次,獲取訓練損失和精度。
- print: 輸出當前輪次的損失和精度。
輸出範例
Epoch 1/3
Train loss: 0.8123, Train accuracy: 0.3333
Epoch 2/3
Train loss: 0.9957, Train accuracy: 0.3333
Epoch 3/3
Train loss: 0.4933, Train accuracy: 0.6667
- Epoch 1/3
- Train loss: 0.8123: 第一輪訓練的平均損失為0.8123。
- Train accuracy: 0.3333: 第一輪訓練的精度為33.33%。
- Epoch 2/3
- Train loss: 0.9957: 第二輪訓練的平均損失為0.9957。
- Train accuracy: 0.3333: 第二輪訓練的精度維持在33.33%。
- Epoch 3/3
- Train loss: 0.4933: 第三輪訓練的平均損失降至0.4933。
- Train accuracy: 0.6667: 第三輪訓練的精度提升至66.67%。
分析:
- 在第三輪,模型的損失顯著下降,精度提升,表明模型在學習和改進。
- 前兩輪精度較低,可能是由於數據量小(僅4個樣本),影響了模型的學習效果。
12. 定義驗證函數
def eval_model(model, data_loader, criterion, device):
model.eval()
total_loss = 0
correct_predictions = 0
with torch.no_grad():
for batch in data_loader:
input_ids = batch['input_ids'].to(device)
attention_mask = batch['attention_mask'].to(device)
labels = batch['labels'].to(device)
outputs = model(input_ids, attention_mask)
loss = criterion(outputs, labels)
total_loss += loss.item()
_, preds = torch.max(outputs, dim=1)
correct_predictions += torch.sum(preds == labels)
avg_loss = total_loss / len(data_loader)
accuracy = correct_predictions.double() / len(data_loader.dataset)
return avg_loss, accuracy
- model.eval(): 設置模型為評估模式,禁用 dropout 等訓練特有的層。
- with torch.no_grad(): 禁用梯度計算,節省資源。
- for batch in data_loader: 遍歷驗證集的每個批次。
- 將
input_ids、attention_mask 和 labels 移動到設備。
- outputs = model(...): 前向傳播,計算 logits。
- loss = criterion(outputs, labels): 計算損失。
- total_loss += loss.item(): 累加損失。
- _, preds = torch.max(outputs, dim=1): 獲取預測標籤。
- correct_predictions += torch.sum(preds == labels): 累加正確預測的數量。
- avg_loss: 計算驗證集的平均損失。
- accuracy: 計算驗證集的精度。
- 返回 平均損失和精度。
13. 執行驗證
val_loss, val_acc = eval_model(model, val_loader, criterion, device)
print(f"Validation loss: {val_loss:.4f}, Validation accuracy: {val_acc:.4f}")
- 調用
eval_model 函數進行模型在驗證集上的評估,獲取驗證損失和精度。
- print: 輸出驗證結果。
輸出範例
Validation loss: 0.5164, Validation accuracy: 1.0000
- Validation loss: 0.5164: 驗證集的平均損失為0.5164。
- Validation accuracy: 1.0000: 驗證集的精度為100%。
分析:
- 驗證集上達到了完美的精度,這可能是由於驗證集樣本極少(僅有20%的數據,對於 4 個樣本來說,可能僅有1個樣本),導致結果不具有代表性。
- 整體而言,由於數據集非常小,訓練和驗證結果的穩定性和可靠性較低。
總結
這段程式碼展示了如何使用 BERT 模型進行中文文本分類的完整流程,包括數據處理、模型定義、訓練和評估。以下是每個主要步驟的總結:
- 加載預訓練模型和分詞器:選擇合適的 BERT 模型(此例中為 'bert-base-chinese'),並使用相應的分詞器將文本轉換為模型輸入格式。
- 數據準備:將文本和標籤準備好,並使用自訂的
TextDataset 類將其轉換為 PyTorch 可處理的數據集。
- 定義模型結構:在預訓練的 BERT 模型基礎上添加分類層,形成完整的分類模型。
- 訓練模型:使用訓練數據進行多輪迭代訓練,通過優化器和損失函數不斷調整模型參數。
- 評估模型:在驗證集上評估模型的性能,以檢查其泛化能力。
需要注意的是,實際應用中需要更大的數據集來訓練和評估模型,以確保結果具有可靠性。此外,還可以進一步調整模型超參數、使用更複雜的訓練策略(如學習率調整、早停等)來提升模型性能。