用於文字處理的 Transformers

Deep Learning for Text with PyTorch

Shubham Jain

Instructor

為什麼用 transformers 做文字處理?

Transformers 標誌

  • 速度快
  • 跨距理解詞與詞關係
  • 近似人類的回應
Deep Learning for Text with PyTorch

Transformer 的組成元件

  • Encoder:處理輸入資料

 

  • Decoder:重建輸出

 

  • 前饋式神經網路:精煉理解

 

  • 位置編碼:確保順序有效

 

  • 多頭注意力:擷取多重訊息或情緒
Deep Learning for Text with PyTorch

準備資料:訓練/測試切分

sentences = ["I love this product", "This is terrible", 
             "Could be better", "This is the best"]
labels = [1, 0, 0, 1]

train_sentences = sentences[:3] train_labels = labels[:3] test_sentences = sentences[3:] test_labels = labels[3:]
Deep Learning for Text with PyTorch

建立 transformer 模型

class TransformerEncoder(nn.Module):

def __init__(self, embed_size, heads, num_layers, dropout): super(TransformerEncoder, self).__init__()
self.encoder = nn.TransformerEncoder( nn.TransformerEncoderLayer(d_model=embed_size, nhead=heads), num_layers=num_layers)
self.fc = nn.Linear(embed_size, 2)
def forward(self, x):
x = self.encoder(x)
x = x.mean(dim=1)
return self.fc(x)
model = TransformerEncoder(embed_size=512, heads=8, num_layers=3, dropout=0.5)
optimizer = optim.Adam(model.parameters(), lr=0.001) criterion = nn.CrossEntropyLoss()
Deep Learning for Text with PyTorch

訓練 transformers

for epoch in range(5):

for sentence, label in zip(train_sentences, train_labels): tokens = sentence.split()
data = torch.stack([token_embeddings[token] for token in tokens], dim=1)
output = model(data)
loss = criterion(output, torch.tensor([label]))
optimizer.zero_grad() loss.backward() optimizer.step() print(f"Epoch {epoch}, Loss: {loss.item()}")
Epoch 0, Loss: 13.788233757019043
Epoch 1, Loss: 3.9480819702148438
Epoch 2, Loss: 2.4790847301483154
Epoch 3, Loss: 1.3020926713943481
Epoch 4, Loss: 0.4660853147506714
Deep Learning for Text with PyTorch

使用 transformers 進行預測

def predict(sentence):
    model.eval()

with torch.no_grad():
tokens = sentence.split() data = torch.stack([token_embeddings.get(token, torch.rand((1, 512))) for token in tokens], dim=1)
output = model(data)
predicted = torch.argmax(output, dim=1)
return "Positive" if predicted.item() == 1 else "Negative"
Deep Learning for Text with PyTorch

對新文字進行預測

sample_sentence = "This product can be better"
print(f"'{sample_sentence}' is {predict(sample_sentence)}")
'This product can be better' is Negative
Deep Learning for Text with PyTorch

一起來練習吧!

Deep Learning for Text with PyTorch

Preparing Video For Download...