-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodels.py
178 lines (151 loc) · 8.13 KB
/
models.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
import pickle
from simple_seq2seq import *
import tensorflow as tf
import numpy as np
from random import randint
import copy
class Model1(object):
def __init__(self, session, data, dictionary, embeddings, embeddings_dim=768, vocabulary_size=30522,
num_units=512,
device="gpu:0",
construct_model=True):
self.vocabulary_size = vocabulary_size
self.dictionary = dictionary
self.embeddings = embeddings
self.embeddings_dim = embeddings_dim
self.session = session
self.device = device
self.max_seq_length = 0
# batch_genrator variables
self.index = 0
self.batch_size = 64
self.num_units = num_units
# corpus
self.input_sequences, self.target_sequences, self.corpus_size = self.data_preprocessing(
data)
# Model
if construct_model:
self.construct_model()
def construct_model(self):
with tf.device(self.device):
# seq_lenght?
self.inputs = tf.placeholder(tf.int32, [self.batch_size, None])
self.targets = tf.placeholder(tf.int32, [self.batch_size, None])
self.target_lengths = tf.placeholder(tf.int32, [self.batch_size])
self.embedding_init = tf.placeholder(tf.float32, [self.vocabulary_size, self.embeddings_dim])
self.embedded_inputs = tf.nn.embedding_lookup(self.embedding_init, self.inputs)
self.embedded_targets = tf.nn.embedding_lookup(self.embedding_init, self.targets)
self.encoder = SimpleLSTMEncoder(num_units=512, batch_size=self.batch_size, depth=2)
# for the purpose of weight sharing
# self.decoder = LSTMDecoderWithAttention(num_units=512, cell=None, batch_size=self.batch_size, depth=1)
self.decoder = LSTMDecoderWithAttention(num_units=512, cell=self.encoder.get_cell(), batch_size=self.batch_size, depth=2)
def initialize(self):
self.session.run(tf.global_variables_initializer())
def data_preprocessing(self, data):
# TODO fix problem here. zero pad sequences with less than max_seq_lenght and concat results of each step of
# target and input are seperated for the sake of generality. in this case it is more memory efficient to use
# from a single list
# for-loop
length = len(data[0])
# last sequence of each list has no following sequence
input_sequences = data[0][:length - 1]
# first element of each list has no previous sequence
target_sequences = data[0][1:]
for i in range(len(data)):
length = len(data[i])
if i >= 1:
# last sequence of each list has no following sequence
input_sequences += data[i][:length - 1]
# first element of each list has no previous sequence
target_sequences += data[i][1:]
corpus_size = len(input_sequences)
print(corpus_size)
# input_sequences, target_sequences = np.array(input_sequences), \
# np.array(target_sequences)
return input_sequences, target_sequences, corpus_size
def next_batch(self):
global next_target_batch, next_input_batch, target_batch_lengths
if self.index < len(self.input_sequences):
next_input_batch = copy.deepcopy(self.input_sequences[self.index:self.index + self.batch_size])
next_target_batch = copy.deepcopy(self.target_sequences[self.index:self.index + self.batch_size])
for i in range(self.batch_size):
if self.max_seq_length < len(next_target_batch[i]) < 50:
self.max_seq_length = len(next_target_batch[i])
target_batch_lengths = [0]
for i in range(self.batch_size):
# length of each target sequence to be used in decoder
if len(next_target_batch[i]) > self.max_seq_length:
target_batch_lengths += [self.max_seq_length]
else:
target_batch_lengths += [len(next_target_batch[i])]
# slicing
if len(next_input_batch[i]) > self.max_seq_length:
next_input_batch[i] = next_input_batch[i][:self.max_seq_length]
# zero padding
elif len(next_input_batch[i]) < self.max_seq_length:
zeros_ = [0 for i in range(self.max_seq_length - len(next_input_batch[i]))]
next_input_batch[i] += zeros_
# slicing
if len(next_target_batch[i]) > self.max_seq_length:
next_target_batch[i] = next_target_batch[i][:self.max_seq_length]
# zero padding
elif len(next_target_batch[i]) < self.max_seq_length:
zeros_ = [0 for i in range(self.max_seq_length - len(next_target_batch[i]))]
next_target_batch[i] += zeros_
self.index = self.index + 1
self.max_seq_length = 0
target_batch_lengths = np.array(target_batch_lengths[1:])
next_input_batch, next_target_batch = np.array(next_input_batch), np.array(next_target_batch)
return next_input_batch, next_target_batch, target_batch_lengths
# TODO separate model from train.
def train(self):
with tf.device(self.device):
with tf.Session.as_default(self.session):
output, final_state = self.encoder(self.embedded_inputs)
print("hhhh", final_state)
final_outputs, final_state, final_sequence_lengths = self.decoder.call(
mode='train',
initial_state=final_state,
encoder_memory=output,
inputs=self.embedded_targets,
input_lengths=self.target_lengths)
# final_outputs, final_state, final_sequence_lengths = self.decoder.call(
# mode='train',
# initial_state=final_state,
# inputs=self.embedded_targets,
# input_lengths=self.target_lengths)
#
mask = tf.sequence_mask(self.target_lengths, dtype=tf.float32,name='masks')
_loss = tf.reduce_mean(tf.contrib.seq2seq.sequence_loss(logits=final_outputs.rnn_output,
targets=self.targets, weights=mask,
average_across_timesteps=True,
average_across_batch=True))
# setting the lr
optimizer = tf.train.AdamOptimizer(learning_rate=0.5, epsilon=0.01).minimize(_loss)
self.session.run(tf.global_variables_initializer())
loss_across = 0
for step in range(self.corpus_size - self.batch_size - 1):
next_input_batch, next_target_batch, target_batch_lengths = self.next_batch()
feed_dict = {self.targets: next_target_batch, self.inputs: next_input_batch,
self.target_lengths: target_batch_lengths, self.embedding_init: self.embeddings}
loss, _ = self.session.run([_loss, optimizer], feed_dict=feed_dict)
loss_across +=loss
if step % 10 == 0:
print('Average loss at step ', step, ': ', loss)
with open("stories.pkl", 'rb') as file:
data = pickle.load(file)
file.close()
# data = [[[k for k in range(randint(j, 2 * j))] for j in range(randint(i, 2 * i))] for i in range(10, 30)]
with open('embeddings_table.pkl', 'rb') as file:
embeddings = pickle.load(file)
file.close()
with open('dictionary.pkl', 'rb') as file:
dictionary = pickle.load(file)
file.close()
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
sess = tf.Session(config=config)
model1 = Model1(session=sess, data=data, dictionary=dictionary, embeddings=embeddings)
model1.train()
saver = tf.train.Saver()
saver.save(sess,"conf/seq2seq_attentiononencoder_weightsharing_depth2.ckpt")