torch LSTM 气温
时间: 2023-08-16 15:13:37 浏览: 95
您好!如果您想使用PyTorch中的LSTM模型来预测气温,我可以为您提供一些代码示例。首先,您需要导入必要的库并准备您的数据。假设您已经有一个包含气温数据的时间序列数据集。以下是一个简单的示例:
```python
import torch
import torch.nn as nn
# 准备数据
data = [30, 32, 35, 28, 24, 26, 30, 32, 35, 28, 24, 26] # 假设这是气温数据
input_seq = torch.tensor(data[:-1]).reshape(-1, 1, 1) # 输入序列 (num_samples, seq_len, input_size)
target_seq = torch.tensor(data[1:]).reshape(-1, 1, 1) # 目标序列 (num_samples, seq_len, input_size)
# 定义LSTM模型
class LSTMModel(nn.Module):
def __init__(self, input_size, hidden_size, num_layers):
super(LSTMModel, self).__init__()
self.hidden_size = hidden_size
self.num_layers = num_layers
self.lstm = nn.LSTM(input_size, hidden_size, num_layers)
self.fc = nn.Linear(hidden_size, input_size)
def forward(self, x):
h0 = torch.zeros(self.num_layers, x.size(1), self.hidden_size).to(x.device)
c0 = torch.zeros(self.num_layers, x.size(1), self.hidden_size).to(x.device)
out, _ = self.lstm(x, (h0, c0))
out = self.fc(out)
return out
# 初始化模型并定义训练参数
input_size = 1
hidden_size = 16
num_layers = 1
model = LSTMModel(input_size, hidden_size, num_layers)
criterion = nn.MSELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.01)
# 训练模型
num_epochs = 1000
for epoch in range(num_epochs):
model.train()
outputs = model(input_seq)
loss = criterion(outputs, target_seq)
optimizer.zero_grad()
loss.backward()
optimizer.step()
if (epoch+1) % 100 == 0:
print(f'Epoch {epoch+1}/{num_epochs}, Loss: {loss.item()}')
# 使用模型进行预测
model.eval()
with torch.no_grad():
predicted_seq = model(input_seq)
print('Predicted Sequence:', predicted_seq.reshape(-1).tolist())
```
请注意,这只是一个简单的示例,您可能需要根据您的具体数据和需求进行调整。希望这可以帮助到您!如果您有任何其他问题,请随时提问。
阅读全文