Я пытаюсь следовать простому руководству по прогнозированию временных рядов LSTM (https://stackabuse.com/time-series-prediction-using-lstm-with-pytorch-in-python/) с использованием Pytorch, в настоящее время я использую только один временной ряд в качестве входных данных, и он работает нормально, но я хочу добавить еще один временной ряд и использовать его в качестве второго входа (я хочу использовать 2 функции для прогнозирования одного выхода), и я не знаю, как это сделать
import torch
import torch.nn as nn
import seaborn as sns
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from pandas import read_csv, read_excel
from sklearn.preprocessing import MinMaxScaler
from torch.utils.tensorboard import SummaryWriter
fig_size = plt.rcParams["figure.figsize"]
fig_size[0] = 15
fig_size[1] = 5
#temp = read_csv('D:/downloads/t.csv')
#temp = temp.iloc[:, 0].values.astype(float)
all_pma = read_excel('D:/downloads/p.xlsx')
all_pma = all_pma.iloc[:, 0].values.astype(float)
#data = np.stack([all_pma, temp], 1)
#data = torch.tensor(data)
test_data_size = 24
train_data = all_pma[:-test_data_size]
test_data = all_pma[-test_data_size:]
scaler = MinMaxScaler(feature_range=(-1, 1))
train_data_normalized = scaler.fit_transform(train_data.reshape(-1, 1))
train_data_normalized = torch.FloatTensor(train_data_normalized).view(-1)
#data_norm = torch.FloatTensor(data_norm).view(-1)
train_window = 24
def create_inout_sequences(input_data, tw):
inout_seq = []
L = len(input_data)
for i in range(L - tw):
train_seq = input_data[i:i + tw]
train_label = input_data[i + tw:i + tw + 1]
inout_seq.append((train_seq, train_label))
return inout_seq
train_inout_seq = create_inout_sequences(train_data_normalized, train_window)
class LSTM(nn.Module):
def __init__(self, input_size=1, hidden_layer_size=100, output_size=1):
super().__init__()
self.hidden_layer_size = hidden_layer_size
self.lstm = nn.LSTM(input_size, hidden_layer_size)
self.linear = nn.Linear(hidden_layer_size, output_size)
self.hidden_cell = (torch.zeros(1, 1, self.hidden_layer_size),
torch.zeros(1, 1, self.hidden_layer_size))
def forward(self, input_seq):
lstm_out, self.hidden_cell = self.lstm(input_seq.view(len(input_seq), 1, -1),
self.hidden_cell)
predictions = self.linear(lstm_out.view(len(input_seq), -1))
return predictions[-1]
model = LSTM()
loss_function = nn.L1Loss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
print(model)
epochs = 1
for i in range(epochs):
for seq, labels in train_inout_seq:
optimizer.zero_grad()
model.hidden_cell = (torch.zeros(1, 1, model.hidden_layer_size),
torch.zeros(1, 1, model.hidden_layer_size))
y_pred = model(seq)
single_loss = loss_function(y_pred, labels)
single_loss.backward()
optimizer.step()
if i % 25 == 1:
print(f'epoch: {i:3} loss: {single_loss.item():10.8f}')
print(f'epoch: {i:3} loss: {single_loss.item():10.10f}')
fut_pred = 24
test_inputs = train_data_normalized[-train_window:].tolist()
print(test_inputs)
model.eval()
for i in range(fut_pred):
seq = torch.FloatTensor(test_inputs[-train_window:])
with torch.no_grad():
model.hidden = (torch.zeros(1, 1, model.hidden_layer_size),
torch.zeros(1, 1, model.hidden_layer_size))
test_inputs.append(model(seq).item())
actual_predictions = scaler.inverse_transform(np.array(test_inputs[train_window:]).reshape(-1, 1))
print('actual predictions :', actual_predictions)
x = np.arange(8759, 8783, 1)
real_values = all_pma[8759:]
rv = np.array(real_values.reshape(-1, 1))
plt.title('Power Consumption')
plt.ylabel('Power Consumption')
plt.grid(True)
plt.autoscale(axis='x', tight=False)
plt.plot(x, rv, color='red')
plt.plot(x, actual_predictions, color='black')
plt.show()