pytoch实现lstm
时间: 2024-04-15 22:31:12 浏览: 49
PyTorch中可以通过`torch.nn.LSTM`类来实现LSTM模型。下面是一个简单的示例代码:
```python
import torch
import torch.nn as nn
class LSTMModel(nn.Module):
def __init__(self, input_size, hidden_size, num_layers, output_size):
super(LSTMModel, 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)
self.fc = nn.Linear(hidden_size, output_size)
def forward(self, x):
h0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(x.device)
c0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(x.device)
out, _ = self.lstm(x, (h0, c0))
out = self.fc(out[:, -1, :])
return out
# 示例用法
input_size = 10
hidden_size = 20
num_layers = 2
output_size = 1
batch_size = 32
sequence_length = 5
model = LSTMModel(input_size, hidden_size, num_layers, output_size)
x = torch.randn(batch_size, sequence_length, input_size)
output = model(x)
print(output.shape)
```
在这个示例代码中,定义了一个名为`LSTMModel`的类,继承自`nn.Module`。在构造函数中,我们初始化了LSTM模型的一些参数,包括输入大小`input_size`、隐藏层大小`hidden_size`、LSTM层数`num_layers`和输出大小`output_size`。然后,我们在`forward`方法中定义了模型的前向传播逻辑,其中使用了`nn.LSTM`和`nn.Linear`两个模型层。
在示例用法中,我们创建了一个输入张量`x`,它的形状是`(batch_size, sequence_length, input_size)`。然后将其传递给LSTM模型,得到输出张量`output`,最后打印输出张量的形状。
希望这个示例对你有帮助!如果你有更多问题,请随时提问。
阅读全文