-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLSTM+Attention.py
365 lines (161 loc) · 4.59 KB
/
LSTM+Attention.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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import tensorflow as tf
print(tf.__version__)
# In[2]:
import string
import requests
# In[3]:
response = requests.get('https://www.gutenberg.org/cache/epub/18993/pg18993.txt')
# In[4]:
response.text
# In[5]:
data = response.text.replace('\r', "").replace("\\'", "'").strip()
data = data.split('\n')
# In[6]:
data[0]
# In[7]:
data[737]
# In[8]:
data = data[737:]
# In[9]:
data[0]
# In[10]:
len(data)
# In[11]:
data = " ".join(data)
# In[12]:
data
# In[13]:
def clean_text(doc):
tokens = doc.split()
table = str.maketrans('','',string.punctuation)
tokens = [(w.translate(table)) for w in tokens]
tokens = [word for word in tokens if word.isalpha()]
tokens = [word.lower() for word in tokens]
return tokens
# In[14]:
tokens = clean_text(data)
# In[15]:
print(tokens[:50])
# In[16]:
len(tokens)
# In[17]:
len(set(tokens))
# In[18]:
length = 50 +1
lines = []
for i in range(length, len(tokens)):
seq = tokens[i-length: i]
line = ' '.join(seq)
lines.append(line)
if i > 200000:
break
# In[19]:
print(len(lines))
# In[20]:
lines[0]
# In[21]:
lines[1]
# In[22]:
import numpy as np
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.utils import to_categorical
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense,LSTM, Embedding
from tensorflow.keras.preprocessing.sequence import pad_sequences
# In[23]:
tokenizer = Tokenizer()
tokenizer.fit_on_texts(lines)
sequences = tokenizer.texts_to_sequences(lines)
# In[24]:
sequences = np.array(sequences)
# In[25]:
sequences
# In[26]:
x = sequences[:, :-1]
y = sequences[:, -1]
# In[27]:
x[0]
# In[28]:
y[0]
# In[29]:
tokenizer.word_index
# In[30]:
len(tokenizer.word_index)
# In[31]:
vocab_size = len(tokenizer.word_index) + 1
# In[32]:
vocab_size
# In[33]:
len(set(tokens))
# In[34]:
y = to_categorical(y, num_classes=vocab_size)
# In[35]:
x.shape[1]
# In[36]:
seq_length = x.shape[1]
# In[37]:
seq_length
# In[38]:
import tensorflow as tf
from tensorflow.keras.layers import Input, Embedding, LSTM, Dense, MultiHeadAttention, LayerNormalization, Dropout
from tensorflow.keras.models import Model
# Define your vocabulary size, sequence lengths, and other hyperparameters
embedding_dim = 50
num_heads = 8
num_lstm_units = 100
# Define input layer
inputs = Input(shape=(seq_length,))
# Embedding layer
embedding_layer = Embedding(input_dim=vocab_size, output_dim=embedding_dim, input_length=seq_length)(inputs)
# Multi-Head Attention Layer
attention_output = MultiHeadAttention(num_heads=num_heads, key_dim=embedding_dim)(embedding_layer, embedding_layer)
# Apply Dropout and Layer Normalization
attention_output = Dropout(0.1)(attention_output)
attention_output = LayerNormalization(epsilon=1e-6)(attention_output + embedding_layer)
# LSTM Layers
lstm_layer1 = LSTM(units=num_lstm_units, return_sequences=True)(attention_output)
lstm_layer2 = LSTM(units=num_lstm_units)(lstm_layer1)
# Dense Layers
dense_layer1 = Dense(units=100, activation='relu')(lstm_layer2)
output_layer = Dense(units=vocab_size, activation='softmax')(dense_layer1)
# Define the model
model = Model(inputs=inputs, outputs=output_layer)
# Compile the model
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
# Summary of the model architecture
model.summary()
# In[39]:
model.summary()
# In[40]:
model.compile(optimizer='adam',loss='categorical_crossentropy',metrics=['accuracy'])
# In[41]:
model.fit(x,y,batch_size=256,epochs=100)
# In[42]:
lines[10299]
# In[43]:
seed_text = lines[10299]
# In[44]:
def generate_text_seq(model, tokenizer, text_seq_length, seed_text, n_words):
text = []
for _ in range(n_words):
encoded = tokenizer.texts_to_sequences([seed_text])[0]
encoded = pad_sequences([encoded], maxlen = text_seq_length, truncating='pre')
y_predict = model.predict(encoded)[0]
predicted_word_idx = np.argmax(y_predict)
predicted_word = ''
for word, index in tokenizer.word_index.items():
if index == predicted_word_idx:
predicted_word = word
break
seed_text = seed_text + ' ' + predicted_word
text.append(predicted_word)
return ' '.join(text)
# In[45]:
generate_text_seq(model, tokenizer, seq_length, seed_text, 10)
# In[46]:
seed_text = 'The german initiated the war because they are'
# In[48]:
generate_text_seq(model, tokenizer, seq_length, seed_text, 10)