I’ve been trying for days to use this trained network to predict future values, I can do the training, and validation, but when it comes to using it to predict future days, I can’t, I would like to know how I use this network already trained to predict values ​​that the network has not yet seen, values ​​for the following days, not validation, in addition to validation, thank you very much ^^
import pandas as pd
import numpy as np
import math
import torch
import matplotlib.pyplot as plt
import yfinance as yf
data = yf.download(‘EURUSD=X’, start=‘2021-01-28’, end=‘2021-02-4’, interval = “1m”)
data = data.Close
torch.cuda.is_available()
device = torch.device(“cuda:0”)
Quantidades total de dados, treinamento e teste.
print(f’Total: {data.size}’)
print(f’Treinamento: {round(data.size*.8)}’)
print(f’Teste: {data.size - round(data.size*.8)}’)
Plotar o gráfico todo
plt.figure  (figsize=(18, 6))
plt.plot    (data, ‘-’)
plt.xlabel  (‘DIAS’)
plt.ylabel  (‘VALOR R$’)
plt.title   (‘PETR4.SA’)
plt.show    ()
Plotar treinamento e teste
plt.figure(figsize=(18, 6))
plt.plot(data[:850], ‘r-’)
plt.plot(data[850:], ‘g-’)
plt.xlabel(‘DIAS’)
plt.ylabel(‘VALOR R$’)
plt.title(‘PETR4.SA’)
plt.axvline(data.index[850], 0, 30, color=‘k’, linestyle=‘dashed’, label=‘Teste’)
plt.text(data.index[320], 25, ‘Treinamento’, fontsize=‘x-large’)
plt.text(data.index[910], 15, ‘Testes’, fontsize=‘x-large’)
plt.show()
Plotar apenas teste
plt.figure(figsize=(10, 6))
plt.plot(data[850:], ‘g-’)
plt.xlabel(‘DIAS’)
plt.ylabel(‘VALOR R$’)
plt.title(‘PETR4.SA’)
plt.show()
Criar janela deslizante
janelas = 50
data_final = np.zeros([data.size - janelas, janelas + 1])
for i in range(len(data_final)):
for j in range(janelas+1):
data_final[i][j] = data.iloc[i+j]
print(data_final[:10])
Normalizar entre 0 e 1
max = data_final.max()
min = data_final.min()
dif = data_final.max() - data_final.min()
data_final = (data_final - data_final.min())/dif
x = data_final[:, :-1]
y = data_final[:,  -1]
print(max, min, dif)
Converter para tensor
#Entrada do treinamento
#Saída do treinamento
training_input  = torch.FloatTensor(x[:850, :])
training_output = torch.FloatTensor(y[:850])
#Entrada do teste
#Saída do teste
test_input  = torch.FloatTensor(x[850: , :])
test_output = torch.FloatTensor(y[850:])
#print(test_input)
#print(test_output)
Classe do modelo da Rede Neural
class Net(torch.nn.Module):
def init(self, input_size, hidden_size):
super(Net, self).init()
self.input_size = input_size
self.hidden_size = hidden_size
self.fc1 = torch.nn.Linear(self.input_size, self.hidden_size)
self.relu = torch.nn.ReLU()
self.fc2 = torch.nn.Linear(self.hidden_size, 1)
def forward(self, x):
hidden = self.fc1(x)
relu = self.relu(hidden)
output = self.fc2(relu)
output = self.relu(output)
return output
def Save(self):
torch.save(model, “NN”)
pass
def Load(self):
    torch.load("NN")
    pass

Criar a instância do modelo
input_size = training_input.size()[1]
hidden_size = 100
model = Net(input_size, hidden_size)
print(f’Entrada: {input_size}’)
print(f’Escondida: {hidden_size}’)
print(model)
Critério de erro
criterion = torch.nn.MSELoss()
Criando os paramêtros (learning rate[obrigatória] e momentum[opcional])
lr = 0.09 #0.01
momentum = 0.03 #0.01
optimizer = torch.optim.SGD(model.parameters(), lr, momentum)
Para visualizar os pesos
for param in model.parameters():
print(param)
pass
Treinamento
model.train()
epochs = 30001
errors = []
for epoch in range(epochs):
optimizer.zero_grad()
Fazer o forward
y_pred = model(training_input)
Cálculo do erro
loss = criterion(y_pred.squeeze(), training_output)
errors.append(loss.item())
if epoch % 1000 == 0:
print(f’Epoch: {epoch}. Train loss: {loss.item()}.’)
Backpropagation
loss.backward()
optimizer.step()
Testar o modelo já treinado
model.eval()
y_pred = model(test_input)
after_train = criterion(y_pred.squeeze(), test_output)
print(‘Test loss after Training’ , after_train.item())
#model.eval()
#y_pred = model(test_input)
#after_train = criterion(y_pred.squeeze(), test_output)
#print(‘Test loss after Training’ , after_train.item())
model.Save()
Gráficos de erro e de previsão
def plotcharts(errors):
errors = np.array(errors)
lasterrors = np.array(errors[-25000:])
plt.figure(figsize=(18, 5))
graf01 = plt.subplot(1, 3, 1) # nrows, ncols, index
graf01.set_title(‘Errors’)
plt.plot(errors, ‘-’)
plt.xlabel(‘Epochs’)
graf02 = plt.subplot(1, 3, 2) # nrows, ncols, index
graf02.set_title(‘Last 25k Errors’)
plt.plot(lasterrors, ‘-’)
plt.xlabel(‘Epochs’)
graf03 = plt.subplot(1, 3, 3)
graf03.set_title(‘Tests’)
a = plt.plot(test_output.numpy(), ‘y-’, label=‘Real’)
#plt.setp(a, markersize=10)
a = plt.plot(y_pred.detach().numpy(), ‘b-’, label=‘Predicted’)
#plt.setp(a, markersize=10)
plt.legend(loc=7)
plt.show()
plotcharts(errors)
################################################################################
###############################################################E################