用于文本分类的迁移学习

使用 PyTorch 的文本深度学习

Shubham Jain

Instructor

什么是迁移学习?

 

迁移学习

  • 将一个任务的已有知识用于相关任务

 

  • 节省时间
  • 共享经验
  • 减少对大数据量的需求

 

  • 英语教师转而教授历史
使用 PyTorch 的文本深度学习

迁移学习的机制

迁移学习 I

使用 PyTorch 的文本深度学习

迁移学习的机制

迁移学习 II

使用 PyTorch 的文本深度学习

迁移学习的机制

迁移学习 II

使用 PyTorch 的文本深度学习

迁移学习的机制

迁移学习 III

使用 PyTorch 的文本深度学习

预训练模型:BERT

  • 来自Transformer的双向编码器表示(BERT)

BERT 情感分析

  • 为语言建模而训练
  • 多层 Transformer
  • 在海量文本上预训练
使用 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)
使用 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
使用 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
使用 PyTorch 的文本深度学习

Passons à la pratique !

使用 PyTorch 的文本深度学习

Preparing Video For Download...