请帮我写一段bi-lstm二分类代码
时间: 2023-12-18 21:04:09 浏览: 89
当然,我可以为您提供一个简单的双向LSTM二分类代码示例。以下是一个使用PyTorch库实现的示例:
```python
import torch
import torch.nn as nn
import torch.optim as optim
# 定义双向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)
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) # 初始化细胞状态
out, _ = self.lstm(x, (h0, c0)) # LSTM前向传播
out = self.fc(out[:, -1, :]) # 取最后一个时间步的输出
return out
# 参数设置
input_size = 10 # 输入维度
hidden_size = 32 # LSTM隐藏层维度
num_layers = 2 # LSTM层数
num_classes = 2 # 分类类别数
learning_rate = 0.001
num_epochs = 5
batch_size = 16
# 创建模型实例
model = BiLSTM(input_size, hidden_size, num_layers, num_classes).to(device)
# 定义损失函数和优化器
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
# 训练模型
total_step = len(train_loader)
for epoch in range(num_epochs):
for i, (inputs, labels) in enumerate(train_loader):
inputs = inputs.to(device)
labels = labels.to(device)
# 前向传播
outputs = model(inputs)
loss = criterion(outputs, labels)
# 反向传播和优化
optimizer.zero_grad()
loss.backward()
optimizer.step()
if (i+1) % 100 == 0:
print('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}'
.format(epoch+1, num_epochs, i+1, total_step, loss.item()))
```
请注意,此代码仅提供了一个基本的框架,您可能需要根据您的数据和具体任务进行适当的修改和调整。
阅读全文