forked from visayang2005/seq2seq_chatterbot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdynamic_seq2seq_model.py
328 lines (271 loc) · 13.1 KB
/
dynamic_seq2seq_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
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
# -*- coding:utf-8 -*-
import math
import numpy as np
import tensorflow as tf
import tensorflow.contrib.seq2seq as seq2seq
from tensorflow.contrib.layers import safe_embedding_lookup_sparse as embedding_lookup_unique
from tensorflow.contrib.rnn import LSTMCell, LSTMStateTuple, GRUCell
class dynamicSeq2seq():
'''
Dynamic_Rnn_Seq2seq with Tensorflow-1.0.0
args:
encoder_cell encoder结构
decoder_cell decoder结构
encoder_vocab_size encoder词典大小
decoder_vocab_size decoder词典大小
embedding_size embedd成的维度
bidirectional encoder的结构
True: encoder为双向LSTM
False: encoder为一般LSTM
attention decoder的结构
True: 使用attention模型
False: 一般seq2seq模型
time_major 控制输入数据格式
True: [time_steps, batch_size]
False: [batch_size, time_steps]
'''
PAD = 0
EOS = 2
UNK = 3
def __init__(self, encoder_cell,
decoder_cell,
encoder_vocab_size,
decoder_vocab_size,
embedding_size,
bidirectional=True,
attention=False,
debug=False,
time_major=False):
self.debug = debug
self.bidirectional = bidirectional
self.attention = attention
self.encoder_vocab_size = encoder_vocab_size
self.decoder_vocab_size = decoder_vocab_size
self.embedding_size = embedding_size
self.encoder_cell = encoder_cell
self.decoder_cell = decoder_cell
self.global_step = tf.Variable(-1, trainable=False)
self.max_gradient_norm = 5
self.time_major = time_major
#创建模型
self._make_graph()
@property
def decoder_hidden_units(self):
# @TODO: is this correct for LSTMStateTuple?
return self.decoder_cell.output_size
def _make_graph(self):
# 创建占位符
self._init_placeholders()
# 兼容decoder输出数据
self._init_decoder_train_connectors()
# embedding层
self._init_embeddings()
# 判断是否为双向LSTM并创建encoder
if self.bidirectional:
self._init_bidirectional_encoder()
else:
self._init_simple_encoder()
# 创建decoder,会判断是否使用attention模型
self._init_decoder()
# 计算loss及优化
self._init_optimizer()
def _init_placeholders(self):
self.encoder_inputs = tf.placeholder(
shape=(None, None),
dtype=tf.int32,
name='encoder_inputs',
)
#self.encoder_inputs = tf.Variable(np.ones((10, 50)).astype(np.int32))
self.encoder_inputs_length = tf.placeholder(
shape=(None,),
dtype=tf.int32,
name='encoder_inputs_length',
)
self.decoder_targets = tf.placeholder(
shape=(None, None),
dtype=tf.int32,
name='decoder_targets'
)
self.decoder_targets_length = tf.placeholder(
shape=(None,),
dtype=tf.int32,
name='decoder_targets_length',
)
def _init_decoder_train_connectors(self):
with tf.name_scope('DecoderTrainFeeds'):
sequence_size, batch_size = tf.unstack(tf.shape(self.decoder_targets))
#batch_size, sequence_size = tf.unstack(tf.shape(self.decoder_targets))
EOS_SLICE = tf.ones([1, batch_size], dtype=tf.int32) * self.EOS
PAD_SLICE = tf.ones([1, batch_size], dtype=tf.int32) * self.PAD
self.decoder_train_inputs = tf.concat([EOS_SLICE, self.decoder_targets], axis=0)
self.decoder_train_length = self.decoder_targets_length + 1
#self.decoder_train_length = self.decoder_targets_length
decoder_train_targets = tf.concat([self.decoder_targets, PAD_SLICE], axis=0)
decoder_train_targets_seq_len, _ = tf.unstack(tf.shape(decoder_train_targets))
decoder_train_targets_eos_mask = tf.one_hot(self.decoder_train_length - 1,
decoder_train_targets_seq_len,
on_value=self.EOS, off_value=self.PAD,
dtype=tf.int32)
decoder_train_targets_eos_mask = tf.transpose(decoder_train_targets_eos_mask, [1, 0])
decoder_train_targets = tf.add(decoder_train_targets,
decoder_train_targets_eos_mask)
self.decoder_train_targets = decoder_train_targets
self.loss_weights = tf.ones([
batch_size,
tf.reduce_max(self.decoder_train_length)
], dtype=tf.float32, name="loss_weights")
def _init_embeddings(self):
with tf.variable_scope("embedding") as scope:
sqrt3 = math.sqrt(3)
initializer = tf.random_uniform_initializer(-sqrt3, sqrt3)
self.encoder_embedding_matrix = tf.get_variable(
name="encoder_embedding_matrix",
shape=[self.encoder_vocab_size, self.embedding_size],
initializer=initializer,
dtype=tf.float32)
self.decoder_embedding_matrix = tf.get_variable(
name="decoder_embedding_matrix",
shape=[self.decoder_vocab_size, self.embedding_size],
initializer=initializer,
dtype=tf.float32)
# encoder的embedd
self.encoder_inputs_embedded = tf.nn.embedding_lookup(
self.encoder_embedding_matrix, self.encoder_inputs)
# decoder的embedd
self.decoder_train_inputs_embedded = tf.nn.embedding_lookup(
self.decoder_embedding_matrix, self.decoder_train_inputs)
def _init_simple_encoder(self):
'''
一般的encdoer
'''
with tf.variable_scope("Encoder") as scope:
(self.encoder_outputs, self.encoder_state) = (
tf.nn.dynamic_rnn(cell=self.encoder_cell,
inputs=self.encoder_inputs_embedded,
sequence_length=self.encoder_inputs_length,
time_major=self.time_major,
dtype=tf.float32)
)
def _init_bidirectional_encoder(self):
'''
双向LSTM encoder
'''
with tf.variable_scope("BidirectionalEncoder") as scope:
((encoder_fw_outputs,
encoder_bw_outputs),
(encoder_fw_state,
encoder_bw_state)) = (
tf.nn.bidirectional_dynamic_rnn(cell_fw=self.encoder_cell,
cell_bw=self.encoder_cell,
inputs=self.encoder_inputs_embedded,
sequence_length=self.encoder_inputs_length,
time_major=self.time_major,
dtype=tf.float32)
)
self.encoder_outputs = tf.concat((encoder_fw_outputs, encoder_bw_outputs), 2)
if isinstance(encoder_fw_state, LSTMStateTuple):
encoder_state_c = tf.concat(
(encoder_fw_state.c, encoder_bw_state.c), 1, name='bidirectional_concat_c')
encoder_state_h = tf.concat(
(encoder_fw_state.h, encoder_bw_state.h), 1, name='bidirectional_concat_h')
self.encoder_state = LSTMStateTuple(c=encoder_state_c, h=encoder_state_h)
elif isinstance(encoder_fw_state, tf.Tensor):
self.encoder_state = tf.concat((encoder_fw_state, encoder_bw_state), 1, name='bidirectional_concat')
def _init_decoder(self):
with tf.variable_scope("Decoder") as scope:
def output_fn(outputs):
self.test_outputs = outputs
return tf.contrib.layers.linear(outputs, self.decoder_vocab_size, scope=scope)
if not self.attention:
decoder_fn_train = seq2seq.simple_decoder_fn_train(encoder_state=self.encoder_state)
decoder_fn_inference = seq2seq.simple_decoder_fn_inference(
output_fn=output_fn,
encoder_state=self.encoder_state,
embeddings=self.decoder_embedding_matrix,
start_of_sequence_id=self.EOS,
end_of_sequence_id=self.EOS,
maximum_length=tf.reduce_max(self.encoder_inputs_length) + 100,
num_decoder_symbols=self.decoder_vocab_size,
)
else:
# attention_states: size [batch_size, max_time, num_units]
attention_states = tf.transpose(self.encoder_outputs, [1, 0, 2])
(attention_keys,
attention_values,
attention_score_fn,
attention_construct_fn) = seq2seq.prepare_attention(
attention_states=attention_states,
attention_option="bahdanau",
num_units=self.decoder_hidden_units,
)
decoder_fn_train = seq2seq.attention_decoder_fn_train(
encoder_state=self.encoder_state,
attention_keys=attention_keys,
attention_values=attention_values,
attention_score_fn=attention_score_fn,
attention_construct_fn=attention_construct_fn,
name='attention_decoder'
)
decoder_fn_inference = seq2seq.attention_decoder_fn_inference(
output_fn=output_fn,
encoder_state=self.encoder_state,
attention_keys=attention_keys,
attention_values=attention_values,
attention_score_fn=attention_score_fn,
attention_construct_fn=attention_construct_fn,
embeddings=self.decoder_embedding_matrix,
start_of_sequence_id=self.EOS,
end_of_sequence_id=self.EOS,
maximum_length=tf.reduce_max(self.encoder_inputs_length) + 100,
num_decoder_symbols=self.decoder_vocab_size,
)
(self.decoder_outputs_train,
self.decoder_state_train,
self.decoder_context_state_train) = (
seq2seq.dynamic_rnn_decoder(
cell=self.decoder_cell,
decoder_fn=decoder_fn_train,
inputs=self.decoder_train_inputs_embedded,
sequence_length=self.decoder_train_length,
time_major=self.time_major,
scope=scope,
)
)
self.decoder_logits_train = output_fn(self.decoder_outputs_train)
self.decoder_prediction_train = tf.argmax(self.decoder_logits_train, axis=-1, name='decoder_prediction_train')
scope.reuse_variables()
(self.decoder_logits_inference,
self.decoder_state_inference,
self.decoder_context_state_inference) = (
seq2seq.dynamic_rnn_decoder(
cell=self.decoder_cell,
decoder_fn=decoder_fn_inference,
time_major=self.time_major,
scope=scope,
)
)
self.decoder_prediction_inference = tf.argmax(self.decoder_logits_inference, axis=-1, name='decoder_prediction_inference')
def _init_MMI(self, logits, targets):
sum_mmi = 0
x_value_list = 1
def _init_optimizer(self):
# 整理输出并计算loss
logits = tf.transpose(self.decoder_logits_train, [1, 0, 2])
targets = tf.transpose(self.decoder_train_targets, [1, 0])
self.logits = tf.transpose(self.decoder_logits_train, [1, 0, 2])
self.targets = tf.transpose(self.decoder_train_targets, [1, 0])
self.loss = seq2seq.sequence_loss(logits=logits, targets=targets,
weights=self.loss_weights)
opt = tf.train.AdamOptimizer()
self.train_op = opt.minimize(self.loss)
# add
params = tf.trainable_variables()
self.gradient_norms = []
self.updates = []
gradients = tf.gradients(self.loss, params)
clipped_gradients, norm = tf.clip_by_global_norm(gradients,
self.max_gradient_norm)
self.gradient_norms.append(norm)
self.updates.append(opt.apply_gradients(
zip(clipped_gradients, params), global_step=self.global_step))
self.saver = tf.train.Saver(tf.global_variables())