Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

memn2n.py 11 KB

You have to be logged in to leave a comment. Sign In
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
  1. from __future__ import print_function
  2. import keras
  3. from keras.models import Sequential, Model
  4. from keras.layers.embeddings import Embedding
  5. from keras.layers import Permute, dot, add, concatenate
  6. from keras.layers import LSTM, Dense, Dropout, Input, Activation, GRU, SimpleRNN
  7. from keras.utils.data_utils import get_file
  8. from keras.preprocessing.sequence import pad_sequences
  9. from functools import reduce
  10. import tarfile
  11. import numpy as np
  12. import re
  13. import IPython
  14. import matplotlib.pyplot as plt
  15. import pandas as pd
  16. def tokenize(sent):
  17. # return [x.strip() for x in re.split('(\W+)?', sent) if x.strip()]
  18. return sent.strip('"(),-').lower().split(" ")
  19. def parse_stories(lines):
  20. '''Parse stories provided in the bAbi tasks format
  21. '''
  22. data = []
  23. story = []
  24. for line in lines:
  25. line = line.decode('utf-8').strip()
  26. nid, line = line.split(' ', 1)
  27. nid = int(nid)
  28. if nid == 1:
  29. story = []
  30. if '\t' in line:
  31. q, a, supporting = line.split('\t')
  32. q = tokenize(q)
  33. # Provide all the substories
  34. substory = [x for x in story if x]
  35. data.append((substory, q, a))
  36. story.append('')
  37. else:
  38. sent = tokenize(line)
  39. story.append(sent)
  40. return data
  41. def get_stories(f):
  42. data = parse_stories(f.readlines())
  43. flatten = lambda data: reduce(lambda x, y: x + y, data)
  44. data = [(flatten(story), q, answer) for story, q, answer in data]
  45. return data
  46. def vectorize_stories(data, word_idx, story_maxlen, query_maxlen):
  47. X = []
  48. Xq = []
  49. Y = []
  50. for story, query, answer in data:
  51. x = [word_idx[w] for w in story]
  52. xq = [word_idx[w] for w in query]
  53. # let's not forget that index 0 is reserved
  54. y = np.zeros(len(word_idx) + 1)
  55. y[word_idx[answer]] = 1
  56. X.append(x)
  57. Xq.append(xq)
  58. Y.append(y)
  59. return (pad_sequences(X, maxlen=story_maxlen),
  60. pad_sequences(Xq, maxlen=query_maxlen), np.array(Y))
  61. class TrainingVisualizer(keras.callbacks.History):
  62. def on_epoch_end(self, epoch, logs={}):
  63. super().on_epoch_end(epoch, logs)
  64. IPython.display.clear_output(wait=True)
  65. pd.DataFrame({key: value for key, value in self.history.items() if key.endswith('loss')}).plot()
  66. axes = pd.DataFrame({key: value for key, value in self.history.items() if key.endswith('acc')}).plot()
  67. axes.set_ylim([0, 1])
  68. plt.show()
  69. try:
  70. path = get_file('babi-tasks-v1-2.tar.gz', origin='https://s3.amazonaws.com/text-datasets/babi_tasks_1-20_v1-2.tar.gz')
  71. except:
  72. print('Error downloading dataset, please download it manually:\n'
  73. '$ wget http://www.thespermwhale.com/jaseweston/babi/tasks_1-20_v1-2.tar.gz\n'
  74. '$ mv tasks_1-20_v1-2.tar.gz ~/.keras/datasets/babi-tasks-v1-2.tar.gz')
  75. raise
  76. tar = tarfile.open(path)
  77. #path = get_file('tasks_1-20_v1-2.tar.gz')
  78. #tar = tarfile.open(path)
  79. #challenge = 'tasks_1-20_v1-2/en-10k/qa1_single-supporting-fact_{}.txt'
  80. challenges = {
  81. # QA1 with 10,000 samples
  82. 'single_supporting_fact_10k': 'tasks_1-20_v1-2/en-10k/qa1_single-supporting-fact_{}.txt',
  83. # QA2 with 10,000 samples
  84. 'two_supporting_facts_10k': 'tasks_1-20_v1-2/en-10k/qa2_two-supporting-facts_{}.txt',
  85. }
  86. challenge_type = 'single_supporting_fact_10k'
  87. challenge = challenges[challenge_type]
  88. print('Extracting stories for the challenge: single_supporting_fact_10k', challenge_type)
  89. train_stories = get_stories(tar.extractfile(challenge.format('train')))
  90. test_stories = get_stories(tar.extractfile(challenge.format('test')))
  91. len(train_stories), len(test_stories)
  92. print('Number of training stories:', len(train_stories))
  93. print('Number of test stories:', len(test_stories))
  94. train_stories[0]
  95. vocab = sorted(reduce(lambda x, y: x | y, (set(story + q + [answer]) for story, q, answer in train_stories + test_stories)))
  96. #vocab = set()
  97. #for story, q, answer in train_stories + test_stories:
  98. # vocab |= set(story + q + [answer])
  99. #vocab = sorted(vocab)
  100. # Reserve 0 for masking via pad_sequences
  101. vocab_size = len(vocab) + 1
  102. story_maxlen = max(map(len, (x for x, _, _ in train_stories + test_stories)))
  103. query_maxlen = max(map(len, (x for _, x, _ in train_stories + test_stories)))
  104. word_idx = dict((c, i + 1) for i, c in enumerate(vocab))
  105. idx_word = dict((i+1, c) for i,c in enumerate(vocab))
  106. inputs_train, queries_train, answers_train = vectorize_stories(train_stories,
  107. word_idx,
  108. story_maxlen,
  109. query_maxlen)
  110. inputs_test, queries_test, answers_test = vectorize_stories(test_stories,
  111. word_idx,
  112. story_maxlen,
  113. query_maxlen)
  114. print('-------------------------')
  115. print('Vocabulary:\n',vocab,"\n")
  116. print('Vocab size:', vocab_size, 'unique words')
  117. print('Story max length:', story_maxlen, 'words')
  118. print('Query max length:', query_maxlen, 'words')
  119. print('Number of training stories:', len(train_stories))
  120. print('Number of test stories:', len(test_stories))
  121. print('-------------------------')
  122. print('-------------------------')
  123. print('inputs: integer tensor of shape (samples, max_length)')
  124. print('inputs_train shape:', inputs_train.shape)
  125. print('inputs_test shape:', inputs_test.shape)
  126. print('input train sample', inputs_train[0,:])
  127. print('-------------------------')
  128. print('-------------------------')
  129. print('queries: integer tensor of shape (samples, max_length)')
  130. print('queries_train shape:', queries_train.shape)
  131. print('queries_test shape:', queries_test.shape)
  132. print('query train sample', queries_train[0,:])
  133. print('-------------------------')
  134. print('-------------------------')
  135. print('answers: binary (1 or 0) tensor of shape (samples, vocab_size)')
  136. print('answers_train shape:', answers_train.shape)
  137. print('answers_test shape:', answers_test.shape)
  138. print('answer train sample', answers_train[0,:])
  139. print('-------------------------')
  140. train_epochs = 10
  141. batch_size = 32
  142. lstm_size = 64
  143. gru_size=64
  144. rnn_size=64
  145. embed_size = 50
  146. dropout_rate = 0.3
  147. # placeholders
  148. input_sequence = Input((story_maxlen,))
  149. question = Input((query_maxlen,))
  150. print('Input sequence:', input_sequence)
  151. print('Question:', question)
  152. # encoders
  153. # embed the input sequence into a sequence of vectors
  154. input_encoder_m = Sequential()
  155. input_encoder_m.add(Embedding(input_dim=vocab_size,
  156. output_dim=embed_size))
  157. input_encoder_m.add(Dropout(dropout_rate))
  158. # output: (samples, story_maxlen, embedding_dim)
  159. # embed the input into a sequence of vectors of size query_maxlen
  160. input_encoder_c = Sequential()
  161. input_encoder_c.add(Embedding(input_dim=vocab_size,
  162. output_dim=query_maxlen))
  163. input_encoder_c.add(Dropout(dropout_rate))
  164. # output: (samples, story_maxlen, query_maxlen)
  165. # embed the question into a sequence of vectors
  166. question_encoder = Sequential()
  167. question_encoder.add(Embedding(input_dim=vocab_size,
  168. output_dim=embed_size,
  169. input_length=query_maxlen))
  170. question_encoder.add(Dropout(dropout_rate))
  171. # output: (samples, query_maxlen, embedding_dim)
  172. # encode input sequence and questions (which are indices)
  173. # to sequences of dense vectors
  174. input_encoded_m = input_encoder_m(input_sequence)
  175. print('Input encoded m', input_encoded_m)
  176. input_encoded_c = input_encoder_c(input_sequence)
  177. print('Input encoded c', input_encoded_c)
  178. question_encoded = question_encoder(question)
  179. print('Question encoded', question_encoded)
  180. # compute a 'match' between the first input vector sequence
  181. # and the question vector sequence
  182. # shape: `(samples, story_maxlen, query_maxlen)
  183. match = dot([input_encoded_m, question_encoded], axes=-1, normalize=False)
  184. print(match.shape)
  185. match = Activation('softmax')(match)
  186. print('Match shape', match.shape)
  187. # add the match matrix with the second input vector sequence
  188. response = add([match, input_encoded_c]) # (samples, story_maxlen, query_maxlen)
  189. response = Permute((2, 1))(response) # (samples, query_maxlen, story_maxlen)
  190. print('Response shape', response)
  191. # concatenate the response vector with the question vector sequence
  192. answer = concatenate([response, question_encoded])
  193. print('Answer shape', answer)
  194. #answer = LSTM(lstm_size)(answer) # Generate tensors of shape 32
  195. #answer = GRU(gru_size)(answer)
  196. answer = SimpleRNN(rnn_size)(answer)
  197. answer = Dropout(dropout_rate)(answer)
  198. answer = Dense(vocab_size)(answer) # (samples, vocab_size)
  199. # we output a probability distribution over the vocabulary
  200. answer = Activation('softmax')(answer)
  201. # build the final model
  202. model = Model([input_sequence, question], answer)
  203. model.compile(optimizer='rmsprop', loss='categorical_crossentropy',
  204. metrics=['accuracy'])
  205. model.summary()
  206. model.fit([inputs_train, queries_train], answers_train, batch_size, train_epochs, callbacks=[TrainingVisualizer()],
  207. validation_data=([inputs_test, queries_test], answers_test))
  208. model.save('model.h5')
  209. for i in range(0,10):
  210. current_inp = test_stories[i]
  211. current_story, current_query, current_answer = vectorize_stories([current_inp], word_idx, story_maxlen, query_maxlen)
  212. current_prediction = model.predict([current_story, current_query])
  213. current_prediction = idx_word[np.argmax(current_prediction)]
  214. print(' '.join(current_inp[0]), ' '.join(current_inp[1]), '| Prediction:', current_prediction, '| Ground Truth:', current_inp[2])
  215. print("-----------------------------------------------------------------------------------------")
  216. print('-------------------------------------------------------------------------------------------')
  217. print('Custom User Queries (Make sure there are spaces before each word)')
  218. while 1:
  219. print('-------------------------------------------------------------------------------------------')
  220. print('Please input a story')
  221. user_story_inp = input().split(' ')
  222. print('Please input a query')
  223. user_query_inp = input().split(' ')
  224. user_story, user_query, user_ans = vectorize_stories([[user_story_inp, user_query_inp, '.']], word_idx, story_maxlen, query_maxlen)
  225. user_prediction = model.predict([user_story, user_query])
  226. user_prediction = idx_word[np.argmax(user_prediction)]
  227. print('Result')
  228. print(' '.join(user_story_inp), ' '.join(user_query_inp), '| Prediction:', user_prediction)
  229. # Mary went to the bathroom . John moved to the hallway . Mary travelled to the office . # Where is Mary ?
  230. # Sandra travelled to the office . John journeyed to the garden .
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...