Jeremiah_

RNN-01

Sep 24th, 2019
178
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.04 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. Created on Sat Sep 21 18:51:46 2019
  5.  
  6. @author: jeremiah
  7. """
  8.  
  9. #%%
  10. import torch
  11. from torch import nn
  12. import numpy as np
  13. import matplotlib.pyplot as plt
  14. %matplotlib inline
  15.  
  16. #%%
  17. plt.figure(figsize=(8,5))
  18.  
  19. seq_len = 20
  20.  
  21. time_steps = np.linspace(0, np.pi, seq_len + 1)
  22. data = np.sin(time_steps)
  23. data.resize((seq_len +1, 1))
  24.  
  25. x = data[:-1]
  26. y = data[1:]
  27.  
  28. plt.plot(time_steps[1:], x, 'r.', label='input, x')
  29. plt.plot(time_steps[1:], y, 'b.', label='input, y')
  30.  
  31. plt.legend(loc='best')
  32. plt.show()
  33.  
  34. #%%
  35. class RNN_Model(nn.Module):
  36.     def __init__(self, input_size, output_size, hidden_dim, n_layers):
  37.         super().__init__()
  38.         self.hidden_dim = hidden_dim
  39.        
  40.         self.rnn = nn.RNN(input_size, hidden_dim, n_layers, batch_first = True)
  41.        
  42.         self.fc = nn.Linear(hidden_dim, output_size)
  43.        
  44.     def forward(self, x, hidden):
  45.         batch_size = x.size(0)
  46.        
  47.         r_out, hidden = self.rnn(x, hidden)
  48.         #print(f'r_out: {r_out.shape}')
  49.         r_out = r_out.view(-1, self.hidden_dim)
  50.         #print(f'r_out_resized: {r_out.shape}')
  51.        
  52.        
  53.         output = self.fc(r_out)
  54.        
  55.         return output, hidden
  56.  
  57. #%%
  58. test_rnn = RNN_Model(1, 1, 10, 2)
  59. print(test_rnn)
  60.  
  61. test_input = torch.Tensor(data).unsqueeze(0)
  62. print(f'Input size: {test_input.size()}')
  63.  
  64. test_out, test_h = test_rnn(test_input, None)
  65. print(f'Output size: {test_out.size()}')
  66. print(f'Hidden state size: {test_h.size()}')
  67.  
  68. #%%
  69. #defining the hyperparameters
  70. input_size = 1
  71. output_size = 1
  72. hidden_dim = 16
  73. n_layers = 1
  74.  
  75. #instanciating the model
  76. rnn = RNN_Model(input_size, output_size, hidden_dim, n_layers)
  77. print(rnn)
  78.  
  79. #defining loss function and optimizer
  80. from torch import optim
  81. criterion = nn.MSELoss()
  82. optimizer = optim.Adam(rnn.parameters(), lr=0.01)
  83.  
  84. #%%
  85. #train the RNN
  86. def train(rnn, n_steps, print_every):
  87.     hidden = None
  88.    
  89.     for n_batch, step in enumerate(range(n_steps)):
  90.         time_steps = np.linspace(step * np.pi, (step+1)*np.pi, seq_len + 1)
  91.         data = np.sin(time_steps)
  92.         data.resize((seq_len + 1, 1))
  93.         x = data[:-1]
  94.         y = data[1:]
  95.        
  96.         x_tensor = torch.Tensor(x).unsqueeze(0)
  97.         y_tensor = torch.Tensor(y)
  98.        
  99.         prediction, hidden = rnn(x_tensor, hidden)
  100.        
  101.         hidden = hidden.data
  102.        
  103.         loss = criterion(prediction, y_tensor)
  104.        
  105.         optimizer.zero_grad()
  106.         loss.backward()
  107.         optimizer.step()
  108.            
  109.         if n_batch % print_every == 0:
  110.             print(f'Loss: {loss.item()}')
  111.             plt.plot(time_steps[1:], x, 'r.', label='input, x')
  112.             plt.plot(time_steps[1:], prediction.data.numpy().flatten(), 'b.', label='prediction, p')
  113.             plt.plot(time_steps[1:], y, 'g.', label='data_to_learn, y')
  114.             plt.legend(loc='best')
  115.             plt.show()
  116.            
  117.     return rnn
  118.  
  119. #%%
  120. n_steps = 1000
  121. print_every = 100
  122.  
  123.  
  124. trained_rnn = train(rnn, n_steps, print_every)
  125.        
  126. #%%
Advertisement
Add Comment
Please, Sign In to add comment