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)
相关推荐
G311354227312 分钟前
大模型不可用时,业务还能不能继续:企业需要设计降级方案
大数据·服务器·数据库·人工智能·深度学习
TechEdu20260613 分钟前
[人工智能]TensorFlow深度学习框架工程实践概览
人工智能·深度学习·ai·tensorflow
一碗白开水一3 小时前
入门实践工程九:基于 BERT 的中文情感分类微调~附:安装依赖库及工程源码
人工智能·深度学习·机器学习·自然语言处理·分类·bert
xiaoxiaoxiaolll3 小时前
AI赋能复合材料力学:神经网络与” 多尺度仿真
人工智能·深度学习·神经网络
卡梅德生物科技小能手5 小时前
卡梅德生物科普 TPBG(滋养层糖蛋白)
经验分享·深度学习·生活
过期的秋刀鱼!8 小时前
公平性偏见与伦理
人工智能·python·深度学习·神经网络·机器学习
想会飞的蒲公英8 小时前
PyTorch 学习率实战:从零理解衰减策略与调度器
人工智能·pytorch·python·深度学习·机器学习
hhzz9 小时前
《深度学习框架PyTorch入门与实践》系列:01-PyTorch入门与环境搭建之从安装到第一个神经网络
人工智能·pytorch·神经网络
John jj10 小时前
拆解 Telegram 群组频道收录市场:三类方案,一个可运行的评分模型,目前TG中文人工评分加模型评分机制——LetsTG收录“快速”、“无门槛”
大数据·后端·python·深度学习·搜索引擎·django·全文检索
又折桃枝换酒钱10 小时前
CycleChart:一个统一的基于一致性学习的双向图表理解与生成框架(翻译与解读)
人工智能·深度学习·学习