| 302 | print 'loss=%f' % loss |
| 303 | |
| 304 | def predict(self): |
| 305 | x = tf.placeholder("float", [None, self.max_seq_len * 2, self.word_vec_dim]) |
| 306 | y = tf.placeholder("float", [None, self.max_seq_len, self.one_hot_word_vectors_dim]) |
| 307 | |
| 308 | weights = { |
| 309 | 'enc2dec': tf.Variable(tf.random_normal([self.word_vec_dim, self.one_hot_word_vectors_dim])), |
| 310 | 'hid2tar': tf.Variable(tf.random_normal([self.n_hidden, self.one_hot_word_vectors_dim])), |
| 311 | } |
| 312 | biases = { |
| 313 | 'enc2dec': tf.Variable(tf.random_normal([self.max_seq_len, self.one_hot_word_vectors_dim])), |
| 314 | 'hid2tar': tf.Variable(tf.random_normal([self.max_seq_len, self.one_hot_word_vectors_dim])), |
| 315 | } |
| 316 | |
| 317 | optimizer, cost, decoder_layer2_outputs = self.model(x, y, weights, biases, training=False) |
| 318 | |
| 319 | init = tf.global_variables_initializer() |
| 320 | sess = tf.Session() |
| 321 | sess.run(init) |
| 322 | saver = tf.train.Saver() |
| 323 | saver.restore(sess, self.model_dir) |
| 324 | |
| 325 | question = '你是谁' |
| 326 | XY = [] # lstm的训练输入 |
| 327 | Y = [] |
| 328 | EOS = [np.ones(self.word_vec_dim)] |
| 329 | question_seq = [np.zeros(self.word_vec_dim)] * self.max_seq_len |
| 330 | segments = jieba.cut(question) |
| 331 | for index, word in enumerate(segments): |
| 332 | if word in self.word_vector_dict: |
| 333 | vec = np.array(self.word_vector_dict[word]) / self.max_abs_weight |
| 334 | # 防止词过多越界 |
| 335 | if self.max_seq_len - index - 1 < 0: |
| 336 | break |
| 337 | question_seq[self.max_seq_len - index - 1] = vec |
| 338 | |
| 339 | xy = question_seq + EOS + [np.zeros(self.word_vec_dim)] * (self.max_seq_len-1) |
| 340 | XY.append(xy) |
| 341 | Y.append([np.zeros(self.one_hot_word_vectors_dim)] * self.max_seq_len) |
| 342 | output_seq = sess.run(decoder_layer2_outputs, feed_dict={x: XY, y: Y}) |
| 343 | print output_seq |
| 344 | for vector in output_seq: |
| 345 | word_id = np.argmax(vector, axis=0) |
| 346 | print self.word_id_word_dict[word_id] |
| 347 | |
| 348 | |
| 349 | def main(op): |