Pushok

Pytorch Sinusoid estimation

Apr 18th, 2018
558
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.73 KB | None | 0 0
  1. import torch
  2. from torch.autograd import Variable
  3. import torch.nn.functional as F
  4. from torchvision import datasets, transforms
  5. import matplotlib.pyplot as plt
  6. import numpy as np
  7. from functools import reduce
  8.  
  9. %matplotlib inline
  10.  
  11. import torch.nn as nn
  12. import torch.nn.functional as F
  13.  
  14. class Model(nn.Module):
  15.     def __init__(self):
  16.         super(Model, self).__init__()
  17.         self.hn_1 = 4
  18.         self.hn_2 = 16
  19.        
  20.         self.gru_1 = torch.nn.GRUCell(1, self.hn_1, bias=True)
  21.         self.gru_2 = torch.nn.GRUCell(self.hn_1, self.hn_2, bias=True)
  22.         self.linear_1 = torch.nn.Linear(self.hn_2, 1)
  23.         self.h_1 = None
  24.         self.h_2 = None
  25.    
  26.     def reset_hidden_state(self):
  27.         self.h_1 = Variable(torch.randn(1, self.hn_1))
  28.         self.h_2 = Variable(torch.randn(1, self.hn_2))
  29.    
  30.     def forward(self, x):
  31.         gru_outputs = []
  32.         for i in range(x.shape[0] - 1):
  33.             self.h_1 = self.gru_1(x[i].view(1, 1), self.h_1)
  34.             self.h_2 = self.gru_2(self.h_1, self.h_2)
  35.             linear_out = self.linear_1(self.h_2)
  36.             gru_outputs.append(linear_out)
  37.            
  38.         return gru_outputs
  39.  
  40.  
  41. def generate_sin(mesh):
  42.     func = np.sin(mesh)*5
  43.     noise = np.random.standard_normal(size=func.shape[0])
  44.     return func# + noise
  45.  
  46. dataset_source = [
  47.     np.arange(np.random.randint(1, 5),  np.random.randint(6, 20), 0.1).astype(np.float32).reshape(-1, 1) for i in range(100)
  48. ]
  49.  
  50. dataset_target = [
  51.     generate_sin(i.squeeze()).astype(np.float32).reshape(-1, 1) for i in dataset_source
  52. ]
  53.  
  54. num_epochs = 100
  55.  
  56. neu = Model()
  57. criterion = torch.nn.MSELoss()
  58. optimizer = torch.optim.Adam(neu.parameters(), lr=0.0001)
  59.  
  60.  
  61. for epoch in range(num_epochs):
  62.     is_last_call = False
  63.     for count, x in enumerate(zip(dataset_source, dataset_target)):
  64.         x_source, x_target = x
  65.         neu.reset_hidden_state()
  66.         optimizer.zero_grad()
  67.        
  68.         x_source = Variable(torch.from_numpy(x_source))
  69.         x_target = Variable(torch.from_numpy(x_target))
  70.        
  71.         outputs = neu(x_source)
  72.         loss = 0
  73.         for i in range(len(outputs)):
  74.             loss += criterion(outputs[i], x_target[i])
  75.         loss.backward(retain_graph=False)
  76.         optimizer.step()
  77.        
  78.         if count == len(dataset) - 1:
  79.             is_first_call = True
  80.     print('loss on epoch {}: {}'.format(epoch, loss.data.numpy()))
  81.  
  82. test_x = np.arange(0, 10, 0.1).astype(np.float32).reshape(-1, 1)
  83. test_y = generate_sin(test_x.squeeze()).astype(np.float32).reshape(-1, 1)
  84. test_pred = np.array([i.data.numpy().squeeze() for i in neu(Variable(torch.from_numpy(test_x)))])
  85.  
  86. plt.figure(figsize=(15, 5))
  87. plt.plot(test_y.squeeze())
  88. plt.plot(test_pred.squeeze())
  89. plt.show()
Advertisement
Add Comment
Please, Sign In to add comment