bilstm python代码
时间: 2024-04-18 12:21:16 浏览: 125
BiLSTM(双向长短时记忆网络)是一种常用的深度学习模型,用于处理序列数据。下面是一个简单的BiLSTM的Python代码示例:
```python
import torch
import torch.nn as nn
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
def forward(self, x):
h0 = torch.zeros(self.num_layers * 2, x.size(0), self.hidden_size).to(device) # 初始化隐藏状态
c0 = torch.zeros(self.num_layers * 2, x.size(0), self.hidden_size).to(device) # 初始化cell状态
out, _ = self.lstm(x, (h0, c0)) # 前向传播
out = self.fc(out[:, -1, :]) # 取最后一个时间步的输出
return out
# 使用示例
input_size = 10 # 输入特征维度
hidden_size = 32 # 隐藏层大小
num_layers = 2 # LSTM层数
num_classes = 2 # 分类类别数
model = BiLSTM(input_size, hidden_size, num_layers, num_classes)
inputs = torch.randn(5, 3, 10) # 输入数据,维度为(batch_size, sequence_length, input_size)
outputs = model(inputs)
print(outputs.shape) # 输出结果的维度为(batch_size, num_classes)
```
这段代码定义了一个BiLSTM模型,包括初始化函数和前向传播函数。在初始化函数中,我们定义了LSTM层和全连接层。在前向传播函数中,我们首先初始化隐藏状态和cell状态,然后通过LSTM层进行前向传播,最后通过全连接层得到输出结果。
阅读全文