PyTorch LSTM 单步、多步时间预测

PyTorch LSTM 单步、多步时间预测

多维输入、多维输出;单步预测、多步滚动预测

python 复制代码
import torch
import torch.nn as nn
import torch.optim as optim

class LSTMModel(nn.Module):
    def __init__(self, input_dim, hidden_dim, num_layers, output_dim):
        super(LSTMModel, self).__init__()
        self.hidden_dim = hidden_dim
        self.num_layers = num_layers
        self.lstm = nn.LSTM(input_dim, hidden_dim, num_layers, batch_first=True)
        self.fc = nn.Linear(hidden_dim, output_dim)

    def forward(self, x):
        h0 = torch.zeros(self.num_layers, x.size(0), self.hidden_dim).to(x.device)
        c0 = torch.zeros(self.num_layers, x.size(0), self.hidden_dim).to(x.device)
        out, _ = self.lstm(x, (h0, c0))
        out = self.fc(out[:, -1, :])
        return out

# 超参数
input_dim = 400
hidden_dim = 64
num_layers = 2
output_dim = 1
num_epochs = 100
learning_rate = 0.001
batch_size = 32

# 初始化模型、损失函数和优化器
model = LSTMModel(input_dim, hidden_dim, num_layers, output_dim)
criterion = nn.MSELoss()
optimizer = optim.Adam(model.parameters(), lr=learning_rate)

# 示例训练代码(假设已经定义了train_loader)
for epoch in range(num_epochs):
    for i, (inputs, labels) in enumerate(train_loader):
        model.train()
        outputs = model(inputs)
        loss = criterion(outputs, labels)
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
        if (i+1) % 100 == 0:
            print(f'Epoch [{epoch+1}/{num_epochs}], Step [{i+1}/{len(train_loader)}], Loss: {loss.item():.4f}')

# 保存模型
torch.save(model.state_dict(), 'lstm_model_single_step.pth')

# 多步预测函数
def multi_step_predict(model, input_seq, future_steps):
    model.eval()  # 切换到评估模式
    predictions = []

    input_seq = input_seq.unsqueeze(0)  # 增加batch维度,shape变为 (1, seq_len, input_dim)

    for _ in range(future_steps):
        with torch.no_grad():  # 禁用梯度计算
            pred = model(input_seq)  # 预测下一个时间步
        predictions.append(pred.item())  # 存储预测值

        # 更新输入序列,将预测值添加到末尾,并移除最早的一个时间步
        input_seq = torch.cat((input_seq[:, 1:, :], pred.unsqueeze(0).unsqueeze(2)), dim=1)

    return predictions

# 示例调用
initial_input_seq = torch.randn(1, 155, 400)  # 假设这是的初始输入
future_steps = 10
predictions = multi_step_predict(model, initial_input_seq, future_steps)
print(predictions)
相关推荐
Ro Jace13 分钟前
脉冲神经网络与神经形态计算异同
人工智能·深度学习·神经网络
weixin_4684668528 分钟前
PyTorch导出ONNX格式分割模型及在C#中调用预测
人工智能·pytorch·深度学习·c#·跨平台·onnx·语义分割
软件算法开发36 分钟前
基于火烈鸟搜索算法的LSTM网络模型(FSA-LSTM)的一维时间序列预测matlab仿真
人工智能·rnn·matlab·lstm·一维时间序列预测·火烈鸟搜索算法·fsa-lstm
硅谷秋水11 小时前
RoboBrain 2.5:视野中的深度,思维中的时间
深度学习·机器学习·计算机视觉·语言模型·机器人
zhangfeng113311 小时前
Warmup Scheduler深度学习训练中,在训练初期使用较低学习率进行预热(Warmup),然后再按照预定策略(如余弦退火、阶梯下降等)衰减学习率的方法
人工智能·深度学习·学习
沃达德软件11 小时前
电信诈骗预警平台功能解析
大数据·数据仓库·人工智能·深度学习·机器学习·数据库开发
青铜弟弟12 小时前
基于物理的深度学习模型
人工智能·深度学习
向量引擎小橙13 小时前
视觉艺术的“奇点”:深度拆解 Gemini-3-Pro-Image-Preview 绘画模型,看这只“香蕉”如何重塑 AI 创作逻辑!
人工智能·python·gpt·深度学习·llama
byzh_rc14 小时前
[深度学习网络从入门到入土] 网络中的网络NiN
网络·人工智能·深度学习
Piar1231sdafa15 小时前
深度学习目标检测算法之YOLOv26加拿大鹅检测
深度学习·算法·目标检测