Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
deeplearningzerotoall
GitHub Repository: deeplearningzerotoall/PyTorch
Path: blob/master/RNN/season1_refactored/RNN_intro_3.py
631 views
1
# Lab 12 RNN
2
import torch
3
import torch.nn as nn
4
5
torch.manual_seed(777) # reproducibility
6
7
8
idx2char = ['h', 'i', 'e', 'l', 'o']
9
10
# Teach hihell -> ihello
11
x_data = [[0, 1, 0, 2, 3, 3]] # hihell
12
x_one_hot = [[[1, 0, 0, 0, 0], # h 0
13
[0, 1, 0, 0, 0], # i 1
14
[1, 0, 0, 0, 0], # h 0
15
[0, 0, 1, 0, 0], # e 2
16
[0, 0, 0, 1, 0], # l 3
17
[0, 0, 0, 1, 0]]] # l 3
18
19
y_data = [1, 0, 2, 3, 3, 4] # ihello
20
21
# As we have one batch of samples, we will change them to variables only once
22
inputs = torch.Tensor(x_one_hot)
23
labels = torch.LongTensor(y_data)
24
25
num_classes = 5
26
input_size = 5 # one-hot size
27
hidden_size = 5 # output from the LSTM. 5 to directly predict one-hot
28
batch_size = 1 # one sentence
29
sequence_length = 6 # |ihello| == 6
30
num_layers = 1 # one-layer rnn
31
32
33
class RNN(nn.Module):
34
35
def __init__(self, num_classes, input_size, hidden_size, num_layers):
36
super(RNN, self).__init__()
37
38
self.num_classes = num_classes
39
self.num_layers = num_layers
40
self.input_size = input_size
41
self.hidden_size = hidden_size
42
self.sequence_length = sequence_length
43
44
self.rnn = nn.RNN(input_size=self.input_size,
45
hidden_size=self.hidden_size,
46
batch_first=True)
47
48
def forward(self, x):
49
# Initialize hidden and cell states
50
# (num_layers * num_directions, batch, hidden_size) for batch_first=True
51
h_0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size)
52
53
# Propagate input through RNN
54
# Input: (batch, seq_len, input_size)
55
# h_0: (num_layers * num_directions, batch, hidden_size)
56
57
out, _ = self.rnn(x, h_0)
58
return out.view(-1, self.num_classes)
59
60
61
# Instantiate RNN model
62
rnn = RNN(num_classes, input_size, hidden_size, num_layers)
63
print(rnn)
64
65
# Set loss and optimizer function
66
# CrossEntropyLoss = LogSoftmax + NLLLoss
67
criterion = torch.nn.CrossEntropyLoss()
68
optimizer = torch.optim.Adam(rnn.parameters(), lr=0.1)
69
70
# Train the model
71
for epoch in range(100):
72
outputs = rnn(inputs)
73
optimizer.zero_grad()
74
loss = criterion(outputs, labels)
75
loss.backward()
76
optimizer.step()
77
_, idx = outputs.max(1)
78
idx = idx.data.numpy()
79
result_str = ''.join(idx2char[c] for c in idx.squeeze())
80
print(f'epoch: {epoch + 1}, loss: {loss.item():1.3f}')
81
print("Predicted string: ", result_str)
82
83
print("Learning finished!")
84