Advertisement
Guest User

Untitled

a guest
May 19th, 2019
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.03 KB | None | 0 0
  1. import torch
  2. import torch.nn as nn
  3. import torch.optim as optim
  4. import torch.nn.functional as functional
  5. import pandas as pd
  6. import numpy as np
  7. import torch.utils.data as data_utils
  8. from torch.autograd import Variable
  9. import torch.nn.functional as F
  10. import math
  11. import matplotlib.pyplot as plt
  12.  
  13. class NARX(nn.Module):
  14.     def __init__(self, in_variables, hidden_size, out_size):
  15.         super(NARX, self).__init__()
  16.         self.hidden = nn.Sequential(nn.Linear(in_variables + out_size, hidden_size), nn.Tanh())
  17.         self.out = nn.Linear(hidden_size, out_size)
  18.         self.out_size = out_size
  19.  
  20.     def forward(self, sequence):
  21.         y = torch.zeros((sequence.shape[1], self.out_size))
  22.         for x in sequence:
  23.             x = x * 0.5
  24.             y = y * 0.5
  25.             print(x.shape)
  26.             print(y.shape)
  27.             x = torch.cat((x, y), dim=1)
  28.             x = self.hidden(x)
  29.             x = self.out(x)
  30.         return x
  31.  
  32. df = pd.read_csv("C:/Users/Piotrek/Documents/magisterka/dataframe1p.csv", encoding = "ISO-8859-1")
  33. df2 = pd.read_csv("C:/Users/Piotrek/Documents/magisterka/dataframe1s.csv", encoding = "ISO-8859-1")
  34.  
  35. df3 = pd.read_csv("C:/Users/Piotrek/Documents/magisterka/dataframe1pt.csv", encoding = "ISO-8859-1")
  36. df4 = pd.read_csv("C:/Users/Piotrek/Documents/magisterka/dataframe1st.csv", encoding = "ISO-8859-1")
  37.  
  38. def chunks(l, n):
  39.     # For item i in a range that is a length of l,
  40.     for i in range(0, len(l), n):
  41.         # Create an index range for l of n items:
  42.         yield l[i:i+n]
  43.  
  44. class DatasetRNN(data_utils.TensorDataset):
  45.  
  46.     ##  Constructor
  47.     def __init__(self, features, target, sequence_length=1):
  48.         self.features = torch.split(features, sequence_length,dim = 0)
  49.         self.target = torch.split(target, sequence_length,dim = 0)
  50.         self.seq_length = sequence_length
  51.  
  52.     ##  Override total dataset's length getter
  53.     def __len__(self):
  54.         return self.features.__len__()
  55.  
  56.     ##  Override single items' getter
  57.     def __getitem__(self, idx):
  58.         return self.features[idx], self.target[idx][-1]
  59.  
  60. WLevel = df['WLevel']
  61. del df['WLevel']
  62. train = DatasetRNN(torch.Tensor(np.array(df)), torch.Tensor(np.array(WLevel)),10)
  63. train_loader = data_utils.DataLoader(train, batch_size = 200, shuffle = False)
  64. time = list(chunks(df2['time'],200))
  65.  
  66. WLevel2 = np.array(df3['WLevel'])
  67. del df3['WLevel']
  68. test = np.array(df3)
  69. t2 = np.array(df4['time'])
  70.  
  71. input_size = 5
  72.  
  73. def accuracy(model, data_x, data_y, pct_close, tm):
  74.   n_items = len(data_y)
  75.   X = torch.Tensor(data_x)  # 2-d Tensor
  76.   Y = torch.Tensor(data_y)  # actual as 1-d Tensor
  77.   oupt = model(X)       # all predicted as 2-d Tensor
  78.   pred = oupt.view(n_items)  # all predicted as 1-d
  79.   diff = Y-pred
  80.   plt.figure(0)
  81.   plt.plot (tm, Y.detach().numpy(),'b', linewidth = 0.5)
  82.   plt.plot (tm, pred.detach().numpy(),'g', linewidth = 0.5)
  83.   plt.show
  84.   plt.savefig('filename2.png', dpi=1500)
  85.   plt.figure(1)
  86.   plt.plot (tm, diff.detach().numpy(),'b', linewidth = 0.5)
  87.   plt.show
  88.   plt.savefig('filename21.png', dpi=1500)
  89.   n_correct = torch.sum((torch.abs(pred - Y) < torch.abs(pct_close * Y)))
  90.   result = (n_correct.item() * 100.0 / n_items)  # scalar
  91.   MSE = (torch.sum((Y - pred) ** 2))/n_items
  92.   MADE = (torch.sum(torch.abs(Y-pred)))/n_items
  93.   MAPE = 100*(torch.sum((torch.abs(Y-pred))/(torch.max(Y)-torch.min(Y))))/n_items
  94.   VAR = (torch.sum((pred - torch.mean(pred))**2))/(n_items-1)
  95.   return result, MSE.item(), MADE.item(), MAPE.item(), VAR.item()
  96.  
  97. net = NARX(input_size, 7, 1)
  98.  
  99. optimizer = optim.Adam(lr=0.001, params=net.parameters())
  100. loss_func = torch.nn.MSELoss()  # mean squared error
  101.  
  102. i = 0
  103. for features, target in train_loader:
  104.     optimizer.zero_grad()    
  105.     oupt = net(features)
  106.     loss_obj = loss_func(oupt, target)
  107.     loss_obj.backward()
  108.     optimizer.step()
  109.     t=time[i]
  110.     i=i+1
  111.     print("batch = %6d" % i, end="")
  112.     print("  batch loss = %7.4f" % loss_obj.item(), end="")
  113.     net = net.eval()
  114.     #acc = accuracy(net, features, WLevel, 0.1, t)
  115.     net = net.train()
  116.     #print(acc)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement