pytorch 双向lstm代码
时间: 2023-07-31 17:13:07 浏览: 146
下面是使用PyTorch实现双向LSTM的代码示例:
```python
import torch
import torch.nn as nn
# 定义双向LSTM模型
class BiLSTM(nn.Module):
def __init__(self, input_size, hidden_size, num_layers, num_classes):
super(BiLSTM, self).__init__()
self.hidden_size = hidden_size
self.num_layers = num_layers
self.lstm = nn.LSTM(input_size, hidden_size, num_layers, batch_first=True, bidirectional=True)
self.fc = nn.Linear(hidden_size * 2, num_classes) # *2 是因为双向LSTM
def forward(self, x):
h0 = torch.zeros(self.num_layers * 2, x.size(0), self.hidden_size).to(x.device) # 初始隐藏状态,*2 是因为双向LSTM
c0 = torch.zeros(self.num_layers * 2, x.size(0), self.hidden_size).to(x.device) # 初始细胞状态,*2 是因为双向LSTM
out, _ = self.lstm(x, (h0, c0)) # 输出形状:(batch_size, seq_length, hidden_size*2)
out = self.fc(out[:, -1, :]) # 取最后一个时间步的输出作为分类结果
return out
# 定义模型参数
input_size = 10 # 输入特征维度
hidden_size = 20 # LSTM隐藏层维度
num_layers = 2 # LSTM层数
num_classes = 2 # 分类类别数
# 随机生成输入数据
batch_size = 3
seq_length = 5
x = torch.randn(batch_size, seq_length, input_size)
# 创建模型实例并进行前向计算
model = BiLSTM(input_size, hidden_size, num_layers, num_classes)
outputs = model(x)
print(outputs.shape) # 输出形状:(batch_size, num_classes)
```
上述代码定义了一个名为BiLSTM的双向LSTM模型,包含一个双向LSTM层和一个全连接层。在前向计算中,我们首先初始化LSTM的隐藏状态和细胞状态,然后将输入数据传入双向LSTM层,并获取最后一个时间步的输出。最后,将该输出通过全连接层进行分类预测。
阅读全文