完整代码LSTM-attention单变量时间序列预测

import torch
import torch.nn as nn
import pandas as pd
import numpy as np
from sklearn.preprocessing import MinMaxScaler
import matplotlib.pyplot as plt

# 加载数据
data = pd.read_csv('wind_speed_1.csv', header=None)
scaler = MinMaxScaler()
data = scaler.fit_transform(data.values)

# 转换为监督学习问题
def create_dataset(dataset, look_back=10):
    X, y = [], []
    for i in range(len(dataset)-look_back-1):
        X.append(dataset[i:(i+look_back), 0])
        y.append(dataset[i + look_back, 0])
    return torch.tensor(X), torch.tensor(y)

look_back = 10
X, y = create_dataset(data, look_back=look_back)

# 划分训练集和测试集
train_size = int(len(X) * 0.7)
test_size = len(X) - train_size
train_X, test_X = X[:train_size], X[train_size:]
train_y, test_y = y[:train_size], y[train_size:]

# 定义模型
class LSTM_Attention(nn.Module):
    def __init__(self, input_size=1, hidden_size=64, num_layers=1, output_size=1):
        super(LSTM_Attention, 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.attention = nn.Linear(hidden_size, 1)
        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))

        attention_score = self.attention(out)
        attention_weight = torch.softmax(attention_score, dim=1)

        context_vector = attention_weight * out
        context_vector = torch.sum(context_vector, dim=1)

        out = self.fc(context_vector)

        return out

model = LSTM_Attention(input_size=1, hidden_size=64, output_size=1)

# 定义损失函数和优化器
criterion = nn.MSELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)

# 训练模型
num_epochs = 120
batch_size = 64
train_dataset = torch.utils.data.TensorDataset(train_X, train_y)
train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size)
for epoch in range(num_epochs):
    for i, (inputs, labels) in enumerate(train_loader):
        optimizer.zero_grad()

        outputs = model(inputs.unsqueeze(-1).float())
        loss = criterion(outputs.squeeze(), labels.float())

        loss.backward()
        optimizer.step()

    if (epoch+1) % 10 == 0:
        print('Epoch [{}/{}], Loss: {:.4f}'.format(epoch+1, num_epochs, loss.item()))

# 预测并计算误差
with torch.no_grad():
    train_predict = model(train_X.unsqueeze(-1).float()).squeeze().tolist()
    test_predict = model(test_X.unsqueeze(-1).float()).squeeze().tolist()

train_actual = scaler.inverse_transform(train_y.numpy().reshape(-1, 1)).flatten()
test_actual = scaler.inverse_transform(test_y.numpy().reshape(-1, 1)).flatten()
train_predict = scaler.inverse_transform(np.array(train_predict).reshape(-1, 1)).flatten()
test_predict = scaler.inverse_transform(np.array(test_predict).reshape(-1, 1)).flatten()

train_rmse = ((sum([(train_actual[i]-train_predict[i])**2 for i in range(len(train_actual))]))/len(train_actual))**0.5
test_rmse = ((sum([(test_actual[i]-test_predict[i])**2 for i in range(len(test_actual))]))/len(test_actual))**0.5

print('Train RMSE: {:.4f}'.format(train_rmse))
print('Test RMSE: {:.4f}'.format(test_rmse))

# 可视化结果
plt.figure(figsize=(10, 6))
plt.plot(train_actual, label='Actual')
plt.plot(train_predict, label='Predicted')
plt.xlabel('Time (hours)')
plt.ylabel('Wind Speed (m/s)')
plt.title('Training Set')
plt.legend()
plt.show()

plt.figure(figsize=(10, 6))
plt.plot(test_actual,label='Actual')
plt.plot(test_predict, label='Predicted')
plt.xlabel('Time (hours)')
plt.ylabel('Wind Speed (m/s)')
plt.title('Testing Set')
plt.legend()
plt.show()

  • 0
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
以下是一个简的 Matlab 代码示例,用于使用 CNN-LSTM-Attention 模型进行时间序列预测。 首先,我们需要准备我们的数据。我们将使用一个名为“sinwave”的数据集,它是一个正弦曲线的时间序列。 ```matlab % 生成一个正弦波数据集 t = linspace(0, 100, 1000); sinwave = sin(t); ``` 接下来,我们将定义我们的模型架构。我们的模型将由一个卷积层、一个 LSTM 层和一个注意力层组成。 ```matlab % 定义模型架构 layers = [ ... sequenceInputLayer(1) convolution1dLayer(3, 16, 'Padding', 'same') lstmLayer(64, 'OutputMode', 'sequence') attentionLayer('Name', 'attention') fullyConnectedLayer(1) regressionLayer]; ``` 我们将使用“sequenceInputLayer”来定义输入层,它将接受一个时间序列作为输入。然后,我们添加一个卷积层,一个 LSTM 层和一个注意力层。最后,我们添加一个完全连接的层和一个回归层,以便我们可以训练模型进行时间序列预测。 接下来,我们需要定义一些训练参数和选项。 ```matlab % 定义训练参数和选项 options = trainingOptions(... 'adam', ... 'MaxEpochs', 50, ... 'MiniBatchSize', 16, ... 'InitialLearnRate', 0.001, ... 'LearnRateSchedule', 'piecewise', ... 'LearnRateDropFactor', 0.1, ... 'LearnRateDropPeriod', 10, ... 'GradientThreshold', 1, ... 'Shuffle', 'every-epoch', ... 'Verbose', false, ... 'Plots', 'training-progress'); XTrain = sinwave(1:end-1); YTrain = sinwave(2:end); % 将输入序列转换为序列数据存储对象 XTrain = cellstr(num2str(XTrain(:))); XTrain = reshape(XTrain, 1, 1, []); ``` 我们将使用 Adam 优化器,并设置训练的最大时期数为 50。我们还定义了每个 mini-batch 的大小,初始学习率和学习率调度。我们还将设置梯度阈值,以避免梯度爆炸的问题。最后,我们将定义我们的训练数据,即将输入序列和输出序列存储在变量 XTrain 和 YTrain 中。 接下来,我们可以使用“trainNetwork”函数来训练我们的模型。 ```matlab % 训练模型 net = trainNetwork(XTrain, YTrain, layers, options); ``` 最后,我们可以使用训练好的模型来进行预测。 ```matlab % 预测下一个时间步长的值 XTest = sinwave(end); YTest = predict(net, XTest); ``` 注意,这里我们只预测了下一个时间步长的值。如果您想预测多个时间步长的值,则可以使用循环来进行预测。 这是一个简的 Matlab 代码示例,用于使用 CNN-LSTM-Attention 模型进行时间序列预测

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值