What we want to predict in the code below is dataA. dataA is a one-dimensional array with 48240 elements (4/1/2020~12/31/2022, 48 data per day). The following code creates an LSTM code to predict pred\_length(48) from seq\_length(336). The first half 45312 pieces (data from 4/1/2020~10/31/2022) are used for training and the second half 2928 pieces are used for backtesting.
Please modify this code according to the instructions. What we want to predict is still dataA.
We want to add a future covariate, "data\_future" (a one-dimensional array with 48240 elements, just like dataA).
The "data\_future" has a length of seq\_length(336)+pred\_length(48) and can be used to forecast dataA.

Please modify the code below, Step1~7. Please modify and output Steps 1~3 first.

#step1
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
from torch.autograd import Variable

#step2
dataA=pd.read\_csv('all\_mito\_A\_3.csv')["data"].tolist()
device = torch.device("cuda:0" if torch.cuda.is\_available() else "cpu")
seq\_length = 336

#step3
def sliding\_windows(data, seq\_length):
 x = []
 y = []

 for i in range(len(data) - seq\_length - 48):
 \_x = data[i:(i + seq\_length)]
 \_y = data[(i + seq\_length):(i + seq\_length + 48)]
 x.append(\_x)
 y.append(\_y)

 return np.array(x), np.array(y)

sc = MinMaxScaler()
training\_data = sc.fit\_transform(np.array(dataA[:45312]).reshape(-1, 1))
testing\_data = sc.transform(np.array(dataA[45312:]).reshape(-1, 1))

seq\_length = 336
x\_train, y\_train = sliding\_windows(training\_data, seq\_length)
x\_test, y\_test = sliding\_windows(testing\_data, seq\_length)

x\_train = torch.tensor(x\_train).float().to(device)
y\_train = torch.tensor(y\_train).float().to(device)
x\_test = torch.tensor(x\_test).float().to(device)
y\_test = torch.tensor(y\_test).float().to(device)
train\_dataset = torch.utils.data.TensorDataset(x\_train, y\_train)
train\_loader = torch.utils.data.DataLoader(train\_dataset, batch\_size=256, shuffle=True)
#step4
class LSTM(nn.Module):
 def \_\_init\_\_(self, input\_size, hidden\_size, num\_layers, output\_size):
 super(LSTM, self).\_\_init\_\_()
 self.input\_size = input\_size
 self.hidden\_size = hidden\_size
 self.num\_layers = num\_layers
 self.output\_size = output\_size

 self.lstm = nn.LSTM(input\_size, hidden\_size, num\_layers, batch\_first=True)
 self.fc = nn.Linear(hidden\_size, output\_size)

 def forward(self, x):
 h\_0 = Variable(torch.zeros(self.num\_layers, x.size(0), self.hidden\_size)).to(device)
 c\_0 = Variable(torch.zeros(self.num\_layers, x.size(0), self.hidden\_size)).to(device)

 \_, (hn, cn) = self.lstm(x, (h\_0, c\_0))
 out = self.fc(hn[-1])
 return out.view(x.size(0), self.output\_size, 1)
input\_size = 1
hidden\_size = 50
num\_layers = 2
pred\_length = 48

model = LSTM(input\_size, hidden\_size, num\_layers, pred\_length)
model = model.to(device).train()

#step5
criterion = nn.MSELoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)

num\_epochs = 100
for epoch in range(num\_epochs):
 for batch\_X, batch\_y in train\_loader:
 batch\_X, batch\_y = batch\_X.to(device), batch\_y.to(device)
 output = model(batch\_X)
 loss = criterion(output, batch\_y)
 optimizer.zero\_grad()
 loss.backward()
 optimizer.step()
 print(f"Epoch: {epoch+1}, Loss: {loss.item():.4f}")
#step6
backtest\_results = []

for i in range(61): # 61 days from 2022/11/1 to 2022/12/31
 backtest\_start = 45312 + i \* 48
 backtest\_end = backtest\_start + seq\_length
 backtest\_data = sc.transform(np.array(dataA[backtest\_start:backtest\_end]).reshape(-1, 1))
 x\_backtest = torch.tensor([backtest\_data]).float().to(device)
 
 model.eval()
 y\_pred = model(x\_backtest)
 y\_pred = y\_pred.cpu().detach().numpy().reshape(-1, 1)
 y\_pred = sc.inverse\_transform(y\_pred)
 backtest\_results.extend(y\_pred)

actual\_data = dataA[45312+seq\_length:]

#step7
backtest\_results = backtest\_results[:len(actual\_data)]

def mean\_absolute\_percentage\_error(y\_true, y\_pred):
 y\_true, y\_pred = np.array(y\_true), np.array(y\_pred)
 return np.mean(np.abs((y\_true - y\_pred) / y\_true)) \* 100

mape = mean\_absolute\_percentage\_error(actual\_data, backtest\_results)

plt.figure(figsize=(12, 6))
plt.plot(actual\_data, label='Actual mito')
plt.plot(backtest\_results, label='Predicted mito')
plt.xlabel("Time")
plt.ylabel("data")
plt.legend()
plt.title(f"Actual vs Predicted Mito (MAPE: {mape:.2f}%)")
plt.show()
아래 코드에서 예측하고자 하는 데이터는 데이터A입니다. 데이터A는 48240개의 요소(2020년 4월 1일~2022년 12월 31일, 하루에 48개의 데이터)가 있는 1차원 배열입니다. 다음 코드는 seq\_length(336)에서 pred\_length(48)을 예측하는 LSTM 코드를 생성합니다. 전반부 45312개(2020년 4월 1일~2022년 10월 31일 데이터)는 훈련에, 후반부 2928개는 백테스팅에 사용됩니다.이 코드를 지침에 따라 수정하세요. 예측하고자 하는 것은 여전히 데이터A입니다.미래 공변량인 "data\_future"(데이터A와 마찬가지로 48240개의 요소가 있는 1차원 배열)를 추가하려고 합니다."data\_future"의 길이는 seq\_length(336)+pred\_length(48)이며, 데이터A를 예측하는 데 사용할 수 있습니다.아래 코드 1~7단계 중 1~3단계를 먼저 수정하여 출력해 주세요.#step1import torchimport torch.nn as nnimport torch.optim as optimimport numpy as np판다를 pd로 가져옵니다.matplotlib.pyplot을 plt로 가져옵니다.sklearn.preprocessing에서 MinMaxScaler를 가져옵니다.torch.autograd에서 변수 가져오기#step2dataA=pd.read\_csv('all\_mito\_A\_3.csv')["data"].tolist()device = torch.device("cuda:0" if torch.cuda.is\_available() else "cpu")seq\_length = 336#step3def sliding\_windows(data, seq\_length): x = [] y = [] for i in range(len(data) - seq\_length - 48): \_x = data[i:(i + seq\_length)] \_y = data[(i + seq\_length):(i + seq\_length + 48)] x.append(\_x) y.append(\_y) 반환 np.array(x), np.array(y)sc = MinMaxScaler()training\_data = sc.fit\_transform(np.array(dataA[:45312]).reshape(-1, 1))testing\_data = sc.transform(np.array(dataA[45312:]).reshape(-1, 1))seq\_length = 336x\_train, y\_train = sliding\_windows(training\_data, seq\_length)X\_TEST, Y\_TEST = SLIDING\_WINDOWS(TESTING\_DATA, SEQ\_LENGTH)x\_train = torch.tensor(x\_train).float().to(device)y\_train = torch.tensor(y\_train).float().to(device)x\_test = torch.tensor(x\_test).float().to(device)y\_test = torch.tensor(y\_test).float().to(device)train\_dataset = torch.utils.data.TensorDataset(x\_train, y\_train)train\_loader = torch.utils.data.DataLoader(train\_dataset, batch\_size=256, shuffle=True)#step4class LSTM(nn.Module): def \_\_init\_\_(self, input\_size, hidden\_size, num\_layers, output\_size): super(LSTM, self).\_\_init\_\_() self.input\_size = 입력\_size self.hidden\_size = hidden\_size self.num\_layers = num\_layers self.output\_size = 출력\_size self.lstm = nn.LSTM(input\_size, hidden\_size, num\_layers, batch\_first=True) self.fc = nn.Linear(hidden\_size, output\_size) def forward(self, x): h\_0 = Variable(torch.zeros(self.num\_layers, x.size(0), self.hidden\_size)).to(device) c\_0 = Variable(torch.zeros(self.num\_layers, x.size(0), self.hidden\_size)).to(device) \_, (hn, cn) = self.lstm(x, (h\_0, c\_0)) out = self.fc(hn[-1]) 반환 out.view(x.size(0), self.output\_size, 1)input\_size = 1hidden\_size = 50num\_layers = 2pred\_length = 48model = LSTM(input\_size, hidden\_size, num\_layers, pred\_length)model = model.to(device).train()#step5criterion = nn.MSELoss()optimizer = optim.Adam(model.parameters(), lr=0.001)num\_epochs = 100범위(num\_epochs)의 epoch에 대해: for batch\_X, batch\_y in train\_loader: batch\_X, batch\_y = batch\_X.to(device), batch\_y.to(device) 출력 = 모델(배치\_X) 손실 = criterion(출력, 배치\_y) optimizer.zero\_grad() loss.backward() optimizer.step() print(f"Epoch: {epoch+1}, Loss: {loss.item():.4f}")#step6backtest\_results = []FOR I IN RANGE(61): # 2022/11/1부터 2022/12/31까지 61일 backtest\_start = 45312 + i \* 48 backtest\_end = backtest\_start + seq\_length backtest\_data = sc.transform(np.array(dataA[backtest\_start:backtest\_end]).reshape(-1, 1)) x\_backtest = torch.tensor([backtest\_data]).float().to(device)  model.eval() y\_pred = model(x\_backtest) y\_pred = y\_pred.cpu().detach().numpy().reshape(-1, 1) y\_pred = sc.inverse\_transform(y\_pred) 백테스트\_결과.확장(y\_pred)actual\_data = dataA[45312+seq\_length:]#step7backtest\_results = backtest\_results[:len(actual\_data)]def mean\_absolute\_percentage\_error(y\_true, y\_pred): y\_true, y\_pred = np.array(y\_true), np.array(y\_pred) 반환 np.mean(np.abs((y\_true - y\_pred) / y\_true)) \* 100mape = mean\_absolute\_percentage\_error(actual\_data, backtest\_results)plt.figure(figsize=(12, 6))plt.plot(actual\_data, label='실제 미토')plt.plot(backtest\_results, label='예측된 미토')plt.xlabel("시간")plt.ylabel("데이터")plt.legend()plt.title(f"실제 미토 대 예측 미토(MAPE: {mape:.2f}%)")plt.show()