训练用于文本的 CNN 模型
很好,您已经定义了 TextClassificationCNN 类。现在 PyBooks 需要训练该模型,以便针对图书评论的情感分析进行优化。
我们已为您导入以下包:
torch、将 torch.nn 导入为 nn、将 torch.nn.functional 导入为 F、将 torch.optim 导入为 optim。
还已根据参数 vocab_size 和 embed_dim 实例化了一个 TextClassificationCNN(),并保存为 model。
本练习是课程的一部分
使用 PyTorch 的文本深度学习
练习说明
- 定义用于二分类的损失函数,并保存为
criterion。 - 在训练循环开始时将梯度清零。
- 在循环结束时更新参数。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Define the loss function
criterion = nn.____()
optimizer = optim.SGD(model.parameters(), lr=0.1)
for epoch in range(10):
for sentence, label in data:
# Clear the gradients
model.____()
sentence = torch.LongTensor([word_to_ix.get(w, 0) for w in sentence]).unsqueeze(0)
label = torch.LongTensor([int(label)])
outputs = model(sentence)
loss = criterion(outputs, label)
loss.backward()
# Update the parameters
____.____()
print('Training complete!')