开始使用免费开始使用

Transformer 模型的训练与测试

现在已经构建好 TransformerEncoder 模型,PyBooks 的下一步是用示例评论来训练模型并评估其表现。在这些示例评论上训练,将帮助 PyBooks 把握其海量内容库中的情感趋势。一旦模型表现良好,PyBooks 就能自动化情感分析,为读者提供更有见地的推荐与反馈。

以下包已为您导入:torchnnoptim

TransformerEncoder 类的 model 实例、token_embeddings,以及 train_sentencestrain_labelstest_sentencestest_labels 已为您预加载。

本练习是课程的一部分

使用 PyTorch 的文本深度学习

查看课程

练习说明

  • 在训练循环中,将句子切分为标记,并将其嵌入向量堆叠起来。
  • 将梯度清零并执行反向传播。
  • 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)}")
编辑并运行代码