构建用于文本的 LSTM 模型
在 PyBooks,团队一直致力于利用前沿技术来提升用户体验。基于这一愿景,他们给您分配了一项关键任务。团队希望您探索另一种强大的工具:LSTM,以其能够捕捉数据模式中更复杂的关系而闻名。您将继续使用同一个 Newsgroup 数据集,目标不变:将新闻文章分类为 3 个类别:
rec.autos、sci.med 和 comp.graphics。
以下包已为您加载:torch、nn、optim。
本练习是课程的一部分
使用 PyTorch 的文本深度学习
练习说明
- 通过补全 LSTM 层和线性层所需的参数来搭建一个 LSTM 模型。
- 使用必要的参数初始化该模型。
- 训练 LSTM 模型:将梯度清零,然后将输入数据
X_train_seq传入模型。 - 基于预测的
outputs与真实标签计算损失。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Initialize the LSTM and the output layer with parameters
class LSTMModel(nn.Module):
def __init__(self, input_size, hidden_size, num_layers, num_classes):
super(LSTMModel, self).__init__()
self.hidden_size = hidden_size
self.num_layers = num_layers
self.lstm = nn.LSTM(____, ____, ____, batch_first=True)
self.fc = nn.Linear(____, ____)
def forward(self, x):
h0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size)
c0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size)
out, _ = self.lstm(x, (h0, c0))
out = out[:, -1, :]
out = self.fc(out)
return out
# Initialize model with required parameters
lstm_model = LSTMModel(____, ____, ____, ____)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(lstm_model.parameters(), lr=0.01)
# Train the model by passing the correct parameters and zeroing the gradient
for epoch in range(10):
optimizer.____
outputs = lstm_model(____)
loss = criterion(____, y_train_seq)
loss.backward()
optimizer.step()
print(f'Epoch: {epoch+1}, Loss: {loss.item()}')