開始使用免費開始

訓練與測試 Transformer 模型

在已就緒的 TransformerEncoder 模型下,PyBooks 的下一步是用範例評論來訓練模型並評估其效能。透過這些範例評論進行訓練,能協助 PyBooks 掌握其龐大資料庫中的情感走向。只要模型表現良好,PyBooks 就能自動化情感分析,讓讀者獲得更具洞見的推薦與回饋。

以下套件已為你匯入:torchnnoptim

TransformerEncoder 類別的 model 實例、token_embeddings,以及 train_sentencestrain_labelstest_sentencestest_labels 都已預先載入。

本練習屬於課程

Deep Learning for Text with PyTorch

檢視課程

練習說明

  • 在訓練迴圈中,先將句子切分成 token,並將其對應的嵌入向量(embedding)堆疊起來。
  • 將梯度歸零並執行反向傳播。
  • predict 函式中,停用梯度計算,然後取得情感預測。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

for epoch in range(5):  
    for sentence, label in zip(train_sentences, train_labels):
        # Split the sentences into tokens and stack the embeddings
        tokens = ____
        data = torch.____([token_embeddings[token] for token in ____], dim=1)
        output = model(data)
        loss = criterion(output, torch.tensor([label]))
        # Zero the gradients and perform a backward pass
        optimizer.____()
        loss.____()
        optimizer.step()
        print(f"Epoch {epoch}, Loss: {loss.item()}")

def predict(sentence):
    model.eval()
    # Deactivate the gradient computations and get the sentiment prediction.
    with torch.____():
        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.____(output, dim=1)
        return "Positive" if predicted.item() == 1 else "Negative"

sample_sentence = "This product can be better"
print(f"'{sample_sentence}' is {predict(sample_sentence)}")
編輯並執行程式碼