文字分類的遷移學習

Deep Learning for Text with PyTorch

Shubham Jain

Instructor

什麼是遷移學習?

 

遷移學習

  • 將一個任務的既有知識用於相關任務

 

  • 省時
  • 共享專長
  • 減少大型資料需求

 

  • 例如:英文老師改教歷史
Deep Learning for Text with PyTorch

遷移學習的運作機制

遷移學習 I

Deep Learning for Text with PyTorch

遷移學習的運作機制

遷移學習 II

Deep Learning for Text with PyTorch

遷移學習的運作機制

遷移學習 II

Deep Learning for Text with PyTorch

遷移學習的運作機制

遷移學習 III

Deep Learning for Text with PyTorch

預訓練模型:BERT

  • Bidirectional Encoder Representations from Transformers

BERT 情緒分析

  • 以語言建模訓練
  • 多層 transformers 結構
  • 以大量文本預先訓練
Deep Learning for Text with PyTorch

動手做:實作 BERT

texts = ["I love this!", 
         "This is terrible.", 
         "Amazing experience!", 
         "Not my cup of tea."]
labels = [1, 0, 1, 0]

import torch from transformers import BertTokenizer, BertForSequenceClassification
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') model = BertForSequenceClassification.from_pretrained('bert-base-uncased', num_labels=2)
inputs = tokenizer(texts, padding=True, truncation=True, return_tensors="pt", max_length=32) inputs["labels"] = torch.tensor(labels)
Deep Learning for Text with PyTorch

微調 BERT

optimizer = torch.optim.AdamW(model.parameters(), lr=0.00001)
model.train()

for epoch in range(1): outputs = model(**inputs)
loss = outputs.loss loss.backward()
optimizer.step() optimizer.zero_grad()
print(f"Epoch: {epoch+1}, Loss: {loss.item()}")
Epoch: 1, Loss: 0.7061821222305298
Deep Learning for Text with PyTorch

在新文本上評估

text = "I had an awesome day!"
input_eval = tokenizer(text, return_tensors="pt", truncation=True, 
                       padding=True, max_length=128)

outputs_eval = model(**input_eval)
predictions = torch.nn.functional.softmax(outputs_eval.logits, dim=-1)
predicted_label = 'positive' if torch.argmax(predictions) > 0 else 'negative' print(f"Text: {text}\nSentiment: {predicted_label}")
Text: I had an awesome day!
Sentiment: positive
Deep Learning for Text with PyTorch

一起來練習吧!

Deep Learning for Text with PyTorch

Preparing Video For Download...