-
Notifications
You must be signed in to change notification settings - Fork 0
/
ffnn.py
220 lines (186 loc) · 8.18 KB
/
ffnn.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
import numpy as np
import torch
import torch.nn as nn
from torch.nn import init
import torch.optim as optim
import math
import random
import os
import time
from tqdm import tqdm
import json
from argparse import ArgumentParser
unk = '<UNK>'
# Consult the PyTorch documentation for information on the functions used below:
# https://pytorch.org/docs/stable/torch.html
class FFNN(nn.Module):
def __init__(self, input_dim, h):
super(FFNN, self).__init__()
self.h = h
self.W1 = nn.Linear(input_dim, h)
self.activation = nn.ReLU() # The rectified linear unit; one valid choice of activation function
self.output_dim = 5
self.W2 = nn.Linear(h, self.output_dim)
self.softmax = nn.LogSoftmax() # The softmax function that converts vectors into probability distributions; computes log probabilities for computational benefits
self.loss = nn.NLLLoss() # The cross-entropy/negative log likelihood loss taught in class
def compute_Loss(self, predicted_vector, gold_label):
return self.loss(predicted_vector, gold_label)
def forward(self, input_vector):
# Step 1: Obtain the first hidden layer representation
h = torch.matmul(input_vector, self.W1.weight.t()) + self.W1.bias
h = torch.maximum(h, torch.zeros_like(h))
# Step 2: Obtain the output layer representation
z = torch.matmul(h, self.W2.weight.t()) + self.W2.bias
z_max = torch.max(z, dim=0, keepdim=True)[0] # For numerical stability
z_exp = torch.exp(z - z_max)
z_exp_sum = torch.sum(z_exp, dim=0, keepdim=True)
predicted_vector = z_exp / z_exp_sum # Probability distribution
predicted_vector = self.softmax(predicted_vector)
return predicted_vector
# Returns:
# vocab = A set of strings corresponding to the vocabulary
def make_vocab(data):
vocab = set()
for document, _ in data:
for word in document:
vocab.add(word)
return vocab
# Returns:
# vocab = A set of strings corresponding to the vocabulary including <UNK>
# word2index = A dictionary mapping word/token to its index (a number in 0, ..., V - 1)
# index2word = A dictionary inverting the mapping of word2index
def make_indices(vocab):
vocab_list = sorted(vocab)
vocab_list.append(unk)
word2index = {}
index2word = {}
for index, word in enumerate(vocab_list):
word2index[word] = index
index2word[index] = word
vocab.add(unk)
return vocab, word2index, index2word
# Returns:
# vectorized_data = A list of pairs (vector representation of input, y)
def convert_to_vector_representation(data, word2index):
vectorized_data = []
for document, y in data:
vector = torch.zeros(len(word2index))
for word in document:
index = word2index.get(word, word2index[unk])
vector[index] += 1
vectorized_data.append((vector, y))
return vectorized_data
def load_data(train_data, val_data):
with open(train_data) as training_f:
training = json.load(training_f)
with open(val_data) as valid_f:
validation = json.load(valid_f)
tra = []
val = []
for elt in training:
tra.append((elt["text"].split(),int(elt["stars"]-1)))
for elt in validation:
val.append((elt["text"].split(),int(elt["stars"]-1)))
return tra, val
if __name__ == "__main__":
parser = ArgumentParser()
parser.add_argument("-hd", "--hidden_dim", type=int, required = True, help = "hidden_dim")
parser.add_argument("-e", "--epochs", type=int, required = True, help = "num of epochs to train")
parser.add_argument("--train_data", required = True, help = "path to training data")
parser.add_argument("--val_data", required = True, help = "path to validation data")
parser.add_argument("--test_data", default = "to fill", help = "path to test data")
parser.add_argument('--do_train', action='store_true')
args = parser.parse_args()
# fix random seeds
random.seed(42)
torch.manual_seed(42)
# load data
print("========== Loading data ==========")
train_data, valid_data = load_data(args.train_data, args.val_data) # X_data is a list of pairs (document, y); y in {0,1,2,3,4}
vocab = make_vocab(train_data)
vocab, word2index, index2word = make_indices(vocab)
print("========== Vectorizing data ==========")
train_data = convert_to_vector_representation(train_data, word2index)
valid_data = convert_to_vector_representation(valid_data, word2index)
last_train_accuracy = 0
last_validation_accuracy = 0
model = FFNN(input_dim = len(vocab), h = args.hidden_dim)
optimizer = optim.SGD(model.parameters(),lr=0.01, momentum=0.9)
print("========== Training for {} epochs ==========".format(args.epochs))
stopping_condition = False
last_validation_accuracy = 0
last_train_accuracy = 0
stopping_condition = False
last_validation_accuracy = 0
last_train_accuracy = 0
for epoch in range(args.epochs):
if stopping_condition:
break
model.train()
optimizer.zero_grad()
loss = None
correct = 0
total = 0
start_time = time.time()
print("Training started for epoch {}".format(epoch + 1))
random.shuffle(train_data) # Shuffle training data
minibatch_size = 32
N = len(train_data)
# Training phase
for minibatch_index in tqdm(range(N // minibatch_size)):
optimizer.zero_grad()
loss = None
for example_index in range(minibatch_size):
input_vector, gold_label = train_data[minibatch_index * minibatch_size + example_index]
predicted_vector = model(input_vector)
predicted_label = torch.argmax(predicted_vector)
correct += int(predicted_label == gold_label)
total += 1
example_loss = model.compute_Loss(predicted_vector.view(1, -1), torch.tensor([gold_label]))
if loss is None:
loss = example_loss
else:
loss += example_loss
loss = loss / minibatch_size
loss.backward()
optimizer.step()
train_accuracy = correct / total
print("Training completed for epoch {}".format(epoch + 1))
print("Training accuracy for epoch {}: {}".format(epoch + 1, train_accuracy))
print("Training time for this epoch: {}".format(time.time() - start_time))
# Validation phase
model.eval()
loss = None
correct = 0
total = 0
start_time = time.time()
print("Validation started for epoch {}".format(epoch + 1))
for minibatch_index in tqdm(range(len(valid_data) // minibatch_size)):
optimizer.zero_grad()
loss = None
for example_index in range(minibatch_size):
input_vector, gold_label = valid_data[minibatch_index * minibatch_size + example_index]
predicted_vector = model(input_vector)
predicted_label = torch.argmax(predicted_vector)
correct += int(predicted_label == gold_label)
total += 1
example_loss = model.compute_Loss(predicted_vector.view(1, -1), torch.tensor([gold_label]))
if loss is None:
loss = example_loss
else:
loss += example_loss
loss = loss / minibatch_size
validation_accuracy = correct / total
print("Validation completed for epoch {}".format(epoch + 1))
print("Validation accuracy for epoch {}: {}".format(epoch + 1, validation_accuracy))
print("Validation time for this epoch: {}".format(time.time() - start_time))
# Check for overfitting condition
if validation_accuracy < last_validation_accuracy and train_accuracy > last_train_accuracy:
stopping_condition = True
print("Training done to avoid overfitting!")
print("Best validation accuracy is:", last_validation_accuracy)
break
else:
last_validation_accuracy = validation_accuracy
last_train_accuracy = train_accuracy
# write out to results/test.out