开始使用免费开始使用

带注意力机制的 RNN 模型训练与测试

在 PyBooks,团队之前曾构建过一个不含注意力机制的用于词预测的 RNN 模型。这个初始模型称为 rnn_model,已完成训练并预加载为一个实例。您现在的任务是训练新的 RNNWithAttentionModel,并将其预测结果与早先的 rnn_model 进行比较。

已为您预加载以下对象:

  • inputs:由张量构成的输入序列列表
  • targets:包含每个输入序列目标词的张量
  • optimizer:Adam 优化器函数
  • criterion:CrossEntropyLoss 函数
  • pad_sequences:用于对输入序列进行填充以便批处理的函数
  • attention_model:上一练习中定义的模型类
  • rnn_model:PyBooks 团队训练好的 RNN 模型

本练习是课程的一部分

使用 PyTorch 的文本深度学习

查看课程

练习说明

  • 在使用测试数据进行测试前,将 RNN 模型设为评估模式。
  • 将合适的输入传入 RNN 模型,获取 RNN 的输出。
  • 从 RNN 输出中提取预测分数最高的词。
  • 对注意力模型执行相同操作,从注意力输出中提取预测分数最高的词。

交互式实操练习

通过完成这段示例代码来试试这个练习。

for epoch in range(epochs):
    attention_model.train()
    optimizer.zero_grad()
    padded_inputs = pad_sequences(inputs)
    outputs = attention_model(padded_inputs)
    loss = criterion(outputs, targets)
    loss.backward()
    optimizer.step()

for input_seq, target in zip(input_data, target_data):
    input_test = torch.tensor(input_seq, dtype=torch.long).unsqueeze(0)
   	
    #  Set the RNN model to evaluation mode
    rnn_model.____()
    # Get the RNN output by passing the appropriate input 
    rnn_output = ____(____)
    # Extract the word with the highest prediction score 
    rnn_prediction = ix_to_word[torch.____(____).item()]

    attention_model.eval()
    attention_output = attention_model(input_test)
    # Extract the word with the highest prediction score
    attention_prediction = ix_to_word[torch.____(____).item()]

    print(f"\nInput: {' '.join([ix_to_word[ix] for ix in input_seq])}")
    print(f"Target: {ix_to_word[target]}")
    print(f"RNN prediction: {rnn_prediction}")
    print(f"RNN with Attention prediction: {attention_prediction}")
编辑并运行代码