pytorch实现lstm回归
时间: 2023-11-12 21:09:28 浏览: 39
要实现LSTM回归,可以使用PyTorch中的LSTM模型和MSELoss损失函数。以下是一个示例代码:
```python
import torch
import torch.nn as nn
class LSTMRegressor(nn.Module):
def __init__(self, input_dim, hidden_dim, output_dim, num_layers):
super(LSTMRegressor, self).__init__()
self.lstm = nn.LSTM(input_dim, hidden_dim, num_layers)
self.fc = nn.Linear(hidden_dim, output_dim)
def forward(self, x):
lstm_out, _ = self.lstm(x)
out = self.fc(lstm_out[-1])
return out
model = LSTMRegressor(input_dim=1, hidden_dim=32, output_dim=1, num_layers=2)
criterion = nn.MSELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.01)
# 训练模型
for epoch in range(num_epochs):
# 前向传播
y_pred = model(X_train)
# 计算损失
loss = criterion(y_pred, y_train)
# 反向传播
optimizer.zero_grad()
loss.backward()
optimizer.step()
# 打印损失
print('Epoch [{}/{}], Loss: {:.4f}'.format(epoch+1, num_epochs, loss.item()))
# 预测
with torch.no_grad():
y_test_pred = model(X_test)
```
其中,`input_dim`是输入数据的特征维度,`hidden_dim`是LSTM隐藏层的维度,`output_dim`是输出数据的维度,`num_layers`是LSTM的层数。