-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtrain_model.py
212 lines (170 loc) · 6.87 KB
/
train_model.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 2 18:30:43 2018
@author: himanshu
"""
from keras.layers import Input, Embedding, LSTM, Dense, RepeatVector, Bidirectional, Dropout, merge
from keras.optimizers import Adam, SGD
from keras.models import Model
from keras.models import Sequential
from keras.layers import Activation, Dense
from keras.callbacks import EarlyStopping
from keras.preprocessing import sequence
import os
import keras
from importlib import reload
import tensorflow as tf
print(tf.test.gpu_device_name())
import keras.backend as K
import numpy as np
np.random.seed(2018) # for reproducibility
# import cPickle
import _pickle as cPickle
import os
import pandas as pd
import sys
import matplotlib.pyplot as plt
word_embedding_size = 100
sentence_embedding_size = 300
# dictionary_size = T.dscalar()
dictionary_size = 7000
maxlen_input = 50
maxlen_output = 50
num_subsets = 1
Epochs = 50
BatchSize = 2500 # Check the capacity of your GPU
Patience = 0
dropout = .25
n_test = 100
vocabulary_file = '../input/vocabulary/vocabulary_movie'
questions_file = '../input/talk-data-2009/Padded_context_2009'
answers_file = '../input/talk-data-2009/Padded_answers_2009'
weights_file = 'my_model_weights20.h5'
GLOVE_DIR = '../input/glove6b100dtxt'
early_stopping = EarlyStopping(monitor='val_loss', patience=Patience)
def print_result(input):
ans_partial = np.zeros((1,maxlen_input))
ans_partial[0, -1] = 2 # the index of the symbol BOS (begin of sentence)
for k in range(maxlen_input - 1):
ye = model.predict([input, ans_partial])
mp = np.argmax(ye)
ans_partial[0, 0:-1] = ans_partial[0, 1:]
ans_partial[0, -1] = mp
text = ''
for k in ans_partial[0]:
k = k.astype(int)
if k < (dictionary_size-2):
w = vocabulary[k]
text = text + w[0] + ' '
return(text)
# **********************************************************************
# Reading a pre-trained word embedding and addapting to our vocabulary:
# **********************************************************************
embeddings_index = {}
f = open(os.path.join(GLOVE_DIR, 'glove.6B.100d.txt'))
for line in f:
values = line.split()
word = values[0]
coefs = np.asarray(values[1:], dtype='float32')
embeddings_index[word] = coefs
f.close()
print('Found %s word vectors.' % len(embeddings_index))
embedding_matrix = np.zeros((dictionary_size, word_embedding_size))
# Loading our vocabulary:
vocabulary = cPickle.load(open(vocabulary_file, 'rb'))
# Using the Glove embedding:
i = 0
for word in vocabulary:
embedding_vector = embeddings_index.get(word[0])
if embedding_vector is not None:
# words not found in embedding index will be all-zeros.
embedding_matrix[i] = embedding_vector
i += 1
# *******************************************************************
# Keras model of the chatbot:
# *******************************************************************
ad = Adam(lr=0.00005)
input_context = Input(shape=(maxlen_input,), dtype='int32', name='input_context')
input_answer = Input(shape=(maxlen_input,), dtype='int32', name='input_answer')
LSTM_encoder = LSTM(sentence_embedding_size, init= 'lecun_uniform')
LSTM_decoder = LSTM(sentence_embedding_size, init= 'lecun_uniform')
if os.path.isfile(weights_file):
Shared_Embedding = Embedding(output_dim=word_embedding_size, input_dim=dictionary_size, input_length=maxlen_input)
else:
Shared_Embedding = Embedding(output_dim=word_embedding_size, input_dim=dictionary_size, weights=[embedding_matrix], input_length=maxlen_input)
word_embedding_context = Shared_Embedding(input_context)
context_embedding = LSTM_encoder(word_embedding_context)
word_embedding_answer = Shared_Embedding(input_answer)
answer_embedding = LSTM_decoder(word_embedding_answer)
merge_layer = merge([context_embedding, answer_embedding], mode='concat', concat_axis=1)
out = Dense(3500, activation="relu")(merge_layer)
out = Dense(7000, activation="softmax")(out)
model = Model(input=[input_context, input_answer], output = [out])
model.compile(loss='categorical_crossentropy', optimizer=ad)
print('model compiled')
if os.path.isfile(weights_file):
model.load_weights(weights_file)
# ************************************************************************
# Loading the data:
# ************************************************************************
q = cPickle.load(open(questions_file, 'rb'))
a = cPickle.load(open(answers_file, 'rb'))
print('pickle load completed')
n_exem, n_words = a.shape
qt = q[0:n_test,:]
at = a[0:n_test,:]
q = q[n_test + 1:,:]
a = a[n_test + 1:,:]
print('Number of exemples = %d'%(n_exem - n_test))
step = np.around((n_exem - n_test)/num_subsets)
round_exem = step * num_subsets
step = int(step)
# *************************************************************************
# Bot training:
# *************************************************************************
x = range(0,Epochs)
valid_loss = np.zeros(Epochs)
train_loss = np.zeros(Epochs)
for m in range(Epochs):
# Loop over training batches due to memory constraints:
for n in range(0,int(round_exem),int(step)):
q2 = q[n:n+step]
s = q2.shape
count = 0
for i, sent in enumerate(a[n:n+step]):
l = np.where(sent==3) # the position od the symbol EOS
limit = l[0][0]
count += limit + 1
print('count is',count)
Q = np.zeros((count,maxlen_input))
A = np.zeros((count,maxlen_input))
from psutil import virtual_memory
mem = virtual_memory()
print(mem)
Y = np.zeros((count,dictionary_size),dtype = 'uint8')
# Loop over the training examples:
count = 0
for i, sent in enumerate(a[n:n+step]):
ans_partial = np.zeros((1,maxlen_input))
# Loop over the positions of the current target output (the current output sequence):
l = np.where(sent==3) # the position of the symbol EOS
limit = l[0][0]
for k in range(1,limit+1):
# Mapping the target output (the next output word) for one-hot codding:
y = np.zeros((1, dictionary_size))
y[0, sent[k]] = 1
# preparing the partial answer to input:
ans_partial[0,-k:] = sent[0:k]
# training the model for one epoch using teacher forcing:
Q[count, :] = q2[i:i+1]
A[count, :] = ans_partial
Y[count, :] = y
count += 1
print('Training epoch: %d, training examples: %d - %d'%(m,n, n + step))
model.fit([Q, A], Y, batch_size=BatchSize, epochs=1)
test_input = qt[41:42]
print(print_result(test_input))
train_input = q[41:42]
print(print_result(train_input))
model.save_weights(weights_file, overwrite=True)