How to use the trained neural network to predict future values

CaioCampelo: <p>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 ^^</p>
<p>import pandas as pd<br>
import numpy as np<br>
import math<br>
import torch<br>
import matplotlib.pyplot as plt<br>
import yfinance as yf</p>
<p>data = yf.download(‘EURUSD=X’, start=‘2021-01-28’, end=‘2021-02-4’, interval = “1m”)</p>
<p>data = data.Close</p>
<p>torch.cuda.is_available()<br>
device = torch.device(“cuda:0”)</p>
<h1>Quantidades total de dados, treinamento e teste.</h1>
<p>print(f’Total: {data.size}’)<br>
print(f’Treinamento: {round(data.size*.8)}’)<br>
print(f’Teste: {data.size - round(data.size*.8)}’)</p>
<h1>Plotar o gráfico todo</h1>
<p>plt.figure  (figsize=(18, 6))<br>
plt.plot    (data, ‘-’)<br>
plt.xlabel  (‘DIAS’)<br>
plt.ylabel  (‘VALOR R$’)<br>
plt.title   (‘PETR4.SA’)<br>
plt.show    ()</p>
<h1>Plotar treinamento e teste</h1>
<p>plt.figure(figsize=(18, 6))<br>
plt.plot(data[:850], ‘r-’)<br>
plt.plot(data[850:], ‘g-’)<br>
plt.xlabel(‘DIAS’)<br>
plt.ylabel(‘VALOR R$’)<br>
plt.title(‘PETR4.SA’)<br>
plt.axvline(data.index[850], 0, 30, color=‘k’, linestyle=‘dashed’, label=‘Teste’)<br>
plt.text(data.index[320], 25, ‘Treinamento’, fontsize=‘x-large’)<br>
plt.text(data.index[910], 15, ‘Testes’, fontsize=‘x-large’)<br>
plt.show()</p>
<h1>Plotar apenas teste</h1>
<p>plt.figure(figsize=(10, 6))<br>
plt.plot(data[850:], ‘g-’)<br>
plt.xlabel(‘DIAS’)<br>
plt.ylabel(‘VALOR R$’)<br>
plt.title(‘PETR4.SA’)<br>
plt.show()</p>
<h1>Criar janela deslizante</h1>
<p>janelas = 50</p>
<p>data_final = np.zeros([data.size - janelas, janelas + 1])</p>
<p>for i in range(len(data_final)):<br>
for j in range(janelas+1):<br>
data_final[i][j] = data.iloc[i+j]<br>
print(data_final[:10])</p>
<h1>Normalizar entre 0 e 1</h1>
<p>max = data_final.max()<br>
min = data_final.min()<br>
dif = data_final.max() - data_final.min()<br>
data_final = (data_final - data_final.min())/dif</p>
<p>x = data_final[:, :-1]<br>
y = data_final[:,  -1]<br>
print(max, min, dif)</p>
<h1>Converter para tensor</h1>
<p><span class="hashtag">#Entrada</span> do treinamento<br>
<span class="hashtag">#Saída</span> do treinamento<br>
training_input  = torch.FloatTensor(x[:850, :])<br>
training_output = torch.FloatTensor(y[:850])</p>
<p><span class="hashtag">#Entrada</span> do teste<br>
<span class="hashtag">#Saída</span> do teste<br>
test_input  = torch.FloatTensor(x[850: , :])<br>
test_output = torch.FloatTensor(y[850:])</p>
<p><span class="hashtag">#print</span>(test_input)<br>
<span class="hashtag">#print</span>(test_output)</p>
<h1>Classe do modelo da Rede Neural</h1>
<p>class Net(torch.nn.Module):<br>
def <strong>init</strong>(self, input_size, hidden_size):<br>
super(Net, self).<strong>init</strong>()<br>
self.input_size = input_size<br>
self.hidden_size = hidden_size<br>
self.fc1 = torch.nn.Linear(self.input_size, self.hidden_size)<br>
self.relu = torch.nn.ReLU()<br>
self.fc2 = torch.nn.Linear(self.hidden_size, 1)<br>
def forward(self, x):<br>
hidden = self.fc1(x)<br>
relu = self.relu(hidden)<br>
output = self.fc2(relu)<br>
output = self.relu(output)<br>
return output<br>
def Save(self):<br>
torch.save(model, “NN”)<br>
pass</p>
<pre><code>def Load(self):
    torch.load("NN")
    pass
</code></pre>
<h1>Criar a instância do modelo</h1>
<p>input_size = training_input.size()[1]<br>
hidden_size = 100<br>
model = Net(input_size, hidden_size)<br>
print(f’Entrada: {input_size}’)<br>
print(f’Escondida: {hidden_size}’)<br>
print(model)</p>
<h1>Critério de erro</h1>
<p>criterion = torch.nn.MSELoss()</p>
<h1>Criando os paramêtros (learning rate[obrigatória] e momentum[opcional])</h1>
<p>lr = 0.09 <span class="hashtag">#0</span>.01<br>
momentum = 0.03 <span class="hashtag">#0</span>.01<br>
optimizer = torch.optim.SGD(model.parameters(), lr, momentum)</p>
<h1>Para visualizar os pesos</h1>
<p>for param in model.parameters():</p>
<h1>print(param)</h1>
<p>pass</p>
<h1>Treinamento</h1>
<p>model.train()<br>
epochs = 30001<br>
errors = []<br>
for epoch in range(epochs):<br>
optimizer.zero_grad()</p>
<h1>Fazer o forward</h1>
<p>y_pred = model(training_input)</p>
<h1>Cálculo do erro</h1>
<p>loss = criterion(y_pred.squeeze(), training_output)<br>
errors.append(loss.item())<br>
if epoch % 1000 == 0:<br>
print(f’Epoch: {epoch}. Train loss: {loss.item()}.’)</p>
<h1>Backpropagation</h1>
<p>loss.backward()</p>
<p>optimizer.step()</p>
<h1>Testar o modelo já treinado</h1>
<p>model.eval()<br>
y_pred = model(test_input)<br>
after_train = criterion(y_pred.squeeze(), test_output)<br>
print(‘Test loss after Training’ , after_train.item())<br>
<span class="hashtag">#model</span>.eval()<br>
<span class="hashtag">#y_pred</span> = model(test_input)<br>
<span class="hashtag">#after_train</span> = criterion(y_pred.squeeze(), test_output)<br>
<span class="hashtag">#print</span>(‘Test loss after Training’ , after_train.item())<br>
model.Save()</p>
<h1>Gráficos de erro e de previsão</h1>
<p>def plotcharts(errors):<br>
errors = np.array(errors)<br>
lasterrors = np.array(errors[-25000:])<br>
plt.figure(figsize=(18, 5))<br>
graf01 = plt.subplot(1, 3, 1) # nrows, ncols, index<br>
graf01.set_title(‘Errors’)<br>
plt.plot(errors, ‘-’)<br>
plt.xlabel(‘Epochs’)<br>
graf02 = plt.subplot(1, 3, 2) # nrows, ncols, index<br>
graf02.set_title(‘Last 25k Errors’)<br>
plt.plot(lasterrors, ‘-’)<br>
plt.xlabel(‘Epochs’)<br>
graf03 = plt.subplot(1, 3, 3)<br>
graf03.set_title(‘Tests’)<br>
a = plt.plot(test_output.numpy(), ‘y-’, label=‘Real’)<br>
<span class="hashtag">#plt</span>.setp(a, markersize=10)<br>
a = plt.plot(y_pred.detach().numpy(), ‘b-’, label=‘Predicted’)<br>
<span class="hashtag">#plt</span>.setp(a, markersize=10)<br>
plt.legend(loc=7)<br>
plt.show()<br>
plotcharts(errors)</p>
<p>################################################################################<br>
##############################################################<span class="hashtag">#E</span>################</p>

Gerry: <aside class="quote no-group" data-username="CaioCampelo" data-post="1" data-topic="111562">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/letter_avatar_proxy/v4/letter/c/bb73d2/48.png" class="avatar"> CaioCampelo:</div>
<blockquote>
<p>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 ^^</p>
<p>import pandas as pd<br>
import numpy as np<br>
import math<br>
import torch<br>
import matplotlib.pyplot as plt<br>
import yfinance as yf</p>
<p>data = yf.download(‘EURUSD=X’, start=‘2021-01-28’, end=‘2021-02-4’, interval = “1m”)</p>
<p>data = data.Close</p>
<p>torch.cuda.is_available()<br>
device = torch.device(“cuda:0”)</p>
</blockquote>
</aside>
<p>This might help</p>
<pre><code class="lang-auto">net = newff(observations,targets,10);
[net,tr] = train(net,observations',targets');
erg = zeros(size(test_mat,1),1);
for i = 1: size(test_mat,1)
    y = sim(net,test_mat(i,:)');
    erg(i)=find(compet(y));
end
</code></pre>
<p>where <code>observations</code> is your training set <code>targets</code> are the known values of the hindcast and <code>test_mat</code> are the values for the forecast. In <code>erg</code> the predictions for the forecast are stored<a href="https://www.prepaidgiftbalance.vip/" rel="noopener nofollow ugc">.</a></p>

CaioCampelo: <p>hi friend, thank you very much for the reply, I will test today and send you what I manage to do</p>

CaioCampelo: <p>hi friend, I tested several times and i got nothing, is there a better option? Further explained, I can’t find anything about it anywhere</p>