-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.py
289 lines (219 loc) · 12 KB
/
main.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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
## Import relevant libraries and dependencies
import argparse
import numpy as np
import sys
import random
import matplotlib
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
from torch.autograd import Variable
from model import MyLSTM
from sample_generator import SampleGenerator
MAX_INT = sys.maxsize
# Default value: 5
first_k_errors = 5
## Epsilon value -- output threshold (during test time)
epsilon = 0.5
# For GPU usage
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") ## GPU
def get_args ():
parser = argparse.ArgumentParser(description='Let us train an LSTM model.')
## Experiment type
parser.add_argument ('--exp_type', required=True, type=str, default='single', choices=['single', 'distribution', 'window', 'hidden_units'], help='The experiment type.')
## Required params
parser.add_argument ('--language', type=str, default='abc', choices=['ab', 'abc', 'abcd'], help='The language in consideration.')
parser.add_argument ('--distribution', type=str, default=['uniform'], nargs='*', choices = ['uniform', 'u-shaped', 'left-tailed', 'right-tailed'], help='A list of distribution regimes for our training set (e.g. \'uniform\' \'u_shaped\' \'left_tailed\' \'right_tailed\').')
parser.add_argument ('--window', type=int, default=[1,50], nargs='*',help='A list of length windows for our training set (e.g. 1 30 1 50 50 100 for 1-30, 1-50, 50-100).')
parser.add_argument ('--lstm_hunits', type=int, default=[3], nargs='*', help='A list of hidden units for our LSTM for a given language (e.g. 4 10 36).')
## Optional params
parser.add_argument ('--lstm_hlayers', type=int, default=1, help='The number of layers in the LSTM network.')
parser.add_argument ('--sample_size', type=int, default=1000, help='The total number of training samples.')
parser.add_argument ('--n_epochs', type=int, default=150, help='The total number of epochs.')
parser.add_argument ('--n_trials', type=int, default=10, help='The total number of trials.')
parser.add_argument ('--disp_err_n', type=int, default=5, help='The first k error values.')
params, _ = parser.parse_known_args ()
## Print the entire list of parameters
print(params)
return params
def plot_graphs (lang, info, labels, accuracy_vals, loss_vals, window, filename):
accuracy_vals = np.array (accuracy_vals)
domain = list(range(1, accuracy_vals.shape[2] + 1))
## For plotting purposes...
## Uncomment the following line if you would like to bound the plot window by the maximum e_k value (Ref 1)
# max_y = np.max(accuracy_vals) + 10
e_nums = [1, first_k_errors]
## Lower training threshold
border1 = np.ones(len(domain)) * window[0]
## Upper training threshold
border2 = np.ones(len(domain)) * window[1]
for err_n in e_nums:
plt.figure ()
for i in range(len(labels)):
acc = np.array (accuracy_vals[i])
acc_avg = np.average (acc, axis=0).T
loss = np.array (loss_vals[i])
plt.plot (domain, acc_avg[err_n-1], '.-', label=labels[i])
plt.legend(loc='upper left')
if labels != 'window':
plt.plot (domain, border1, 'c-', label='Threshold$_1$')
plt.plot (domain, border2, 'c-', label='Threshold$_2$')
lang_str = '^n'.join(lang + ' ')[:-1]
plt.title('Generalization Graph for ${}$'.format(lang_str))
plt.xlabel ('Epoch Number')
plt.ylabel ('$e_{}$ Value'.format(str(err_n)))
## For plotting purposes (Ref 1)
# plt.ylim ([0, max_y])
plt.savefig('./figures/{}_error_{}'.format(filename, str(err_n)),dpi=256)
return
def single_investigation (lang, distrib, h_layers, h_units, window, sample_size, n_epochs, exp_num):
acc_per_d = []
loss_per_d = []
generator = SampleGenerator(lang)
## If you would like to fix your training set during the entire course of investigation,
## you should uncomment the following line (and comment the same line in the subsequent "for" loop);
## otherwise, each training set will come from the same distribution and same window but be different.
inputs, outputs, s_dst = generator.generate_sample (sample_size, window[0], window[1], distrib, False)
for _ in range(exp_num):
# inputs, outputs, s_dst = generator.generate_sample (sample_size, window[0], window[1], distrib, False)
e_vals, loss_vals = train (generator, distrib, h_layers, h_units, inputs, outputs, n_epochs, 1) # each experiment is unique
acc_per_d.append (e_vals)
loss_per_d.append(loss_vals)
filename = '{}_{}_{}_{}_{}_{}_{}'.format(lang, 'single', distrib, h_layers, h_units, window[0], window[1])
## Uncomment the following line if you would like to save the e_i and loss values.
# np.savez('./results/result_{}.npz'.format(filename), errors = np.array(e_vals), losses = np.array (loss_vals))
trials_label = ['Experiment {}'.format(elt) for elt in range (1, exp_num + 1)]
plot_graphs (lang, 'trials', trials_label, acc_per_d, loss_per_d, window, filename)
return acc_per_d, loss_vals
def hidden_units_investigation (lang, distrib, h_layers, h_units, window, sample_size, n_epochs, exp_num):
acc_per_d = []
loss_per_d = []
generator = SampleGenerator(lang)
## If you would like to fix your training set during the entire course of investigation,
## you should uncomment the following line (and comment the same line in the subsequent "for" loop);
## otherwise, each training set will come from the same distribution and same window but be different.
inputs, outputs, s_dst = generator.generate_sample (sample_size, window[0], window[1], distrib, False)
for hidden_dim in h_units:
# inputs, outputs, s_dst = generator.generate_sample (sample_size, window[0], window[1], distrib, False)
e_vals, loss_vals = train (generator, distrib, h_layers, hidden_dim, inputs, outputs, n_epochs, exp_num)
acc_per_d.append (e_vals)
loss_per_d.append(loss_vals)
filename = '{}_{}_{}_{}_{}_{}'.format(lang, 'hidden', distrib, h_layers, window[0], window[1])
hunits_label = ['{} Hidden Units'.format(val) for val in h_units]
plot_graphs (lang, 'hiddenunits', hunits_label, acc_per_d, loss_per_d, window, filename)
return acc_per_d, loss_vals
def window_investigation (lang, distrib, h_layers, h_units, windows, sample_size, n_epochs, exp_num):
acc_per_d = []
loss_per_d = []
generator = SampleGenerator(lang)
for window in windows:
inputs, outputs, s_dst = generator.generate_sample (sample_size, window[0], window[1], distrib, False)
e_vals, loss_vals = train (generator, distrib, h_layers, h_units, inputs, outputs, n_epochs, exp_num)
acc_per_d.append (e_vals)
loss_per_d.append(loss_vals)
filename = '{}_{}_{}_{}_{}'.format(lang, 'window', distrib, h_layers, h_units)
window_label = ['Window [{}, {}]'.format(elt[0], elt[1]) for elt in windows]
plot_graphs (lang, 'window', window_label, acc_per_d, loss_per_d, [1, 30], filename) # [1, 30] is a random window. We'll ignore it later.
return acc_per_d, loss_vals
def distribution_investigation (lang, distribution, h_layers, h_units, window, sample_size, n_epochs, exp_num):
acc_per_d = []
loss_per_d = []
generator = SampleGenerator(lang)
for distrib in distribution:
inputs, outputs, s_dst = generator.generate_sample (sample_size, window[0], window[1], distrib, False)
e_vals, loss_vals = train (generator, distrib, h_layers, h_units, inputs, outputs, n_epochs, exp_num)
acc_per_d.append (e_vals)
loss_per_d.append(loss_vals)
filename = '{}_{}_{}_{}_{}_{}'.format(lang, 'distrib', h_layers, h_units, window[0], window[1])
distrib_label = [elt.capitalize() for elt in distribution]
plot_graphs (lang, 'distrib', distrib_label, acc_per_d, loss_per_d, window, filename)
return acc_per_d, loss_vals
def test (generator, lstm):
first_errors = []
with torch.no_grad():
for num in range (1, MAX_INT):
temp = generator.generate_sample (1, num, num)
inp, out = temp[0][0], temp[1][0]
input_size = len(inp)
hidden = lstm.init_hidden()
letter_count = 0
for i in range (input_size):
output, hidden = lstm (generator.lineToTensorInput(inp[i]).to(device), (hidden[0].to(device), hidden[1].to(device)))
output = output.cpu()
prediction = np.int_ (output.numpy()[0] >= epsilon)
actual = np.int_ ((generator.lineToTensorOutput(out[i]).to(device)).numpy()[0])
if np.all(np.equal(np.array(prediction), np.array(actual))):
letter_count += 1
if letter_count != input_size:
first_errors.append(num)
if len(first_errors) == first_k_errors:
return first_errors
def train (generator, distrib, h_layers, h_units, inputs, outputs, n_epochs, exp_num):
lang = generator.get_vocab()
vocab_size = len (lang)
training_size = len (inputs)
loss_arr_per_iter = []
first_errors_per_iter = []
for exp in range (exp_num):
print ('Experiment Number: {}'.format(exp+1))
# Create the model
lstm = MyLSTM(h_units, vocab_size, h_layers).to(device)
# In our experiments, a value between 0.01 and 0.001 worked well
learning_rate = .01 ## learning rate
criterion = nn.MSELoss() ## MSE Loss
optim = torch.optim.RMSprop(lstm.parameters(), lr = learning_rate) ## RMSProp optimizer
loss_arr = []
first_errors = []
for it in range(1, n_epochs + 1):
# total loss per epoch
total_loss = 0
for i in range (training_size):
lstm.zero_grad ()
h0, c0 = lstm.init_hidden()
output, hidden = lstm (generator.lineToTensorInput(inputs[i]).to(device), (h0.to(device), c0.to(device)))
target = generator.lineToTensorOutput(outputs[i]).to(device)
# loss for a single sample
loss = criterion (output, target)
loss.backward ()
optim.step ()
total_loss += loss.item()
if i == training_size - 1: ## one full pass of the training set
loss_arr.append (total_loss) ## add loss val
first_errors.append(test(generator, lstm)) ## add e_i vals
loss_arr_per_iter.append (loss_arr)
first_errors_per_iter.append (first_errors)
# print ('Loss array: ', loss_arr)
# print ('Max Gen: ', first_errors)
## We can save the models as we train.
# rnn_path = './lstm_lang{}_distrib_{}_expn_{}.pth'.format(lang, distrib, str(exp))
# torch.save (lstm, rnn_path)
return first_errors_per_iter, loss_arr_per_iter
def main(args):
global first_k_errors
investigation = args.exp_type
lang = args.language
distrib = args.distribution
window = []
for i in range (int(len(args.window)/2)):
window.append([args.window[2 * i], args.window[2 * i + 1]])
n_units = args.lstm_hunits
n_layers = args.lstm_hlayers
s_size = args.sample_size
n_epochs = args.n_epochs
n_trials = args.n_trials
first_k_errors = args.disp_err_n
if investigation == 'distribution':
distribution_investigation (lang, distrib, n_layers, n_units[0], window[0], s_size, n_epochs, n_trials)
elif investigation == 'window':
window_investigation (lang, distrib[0], n_layers, n_units[0], window, s_size, n_epochs, n_trials)
elif investigation == 'hidden_units':
hidden_units_investigation (lang, distrib[0], n_layers, n_units, window[0], s_size, n_epochs, n_trials)
elif investigation == 'single':
single_investigation (lang, distrib[0], n_layers, n_units[0], window[0], s_size, n_epochs, n_trials)
else:
print ('Sorry, we couldn\'t process your input; could you please try again?')
print ('\nGoodbye!..\n')
return
if __name__ == "__main__":
args = get_args ()
main(args)