def main(text, checkpoint_path): q_vocabutil = VocabUtil("./data/xhj_q.vocab") a_vocabutil = VocabUtil("./data/xhj_a.vocab") tf.reset_default_graph() # 定义训练用的循环神经网络模型。 with tf.variable_scope("nmt_model", reuse=None): model = NMTModel() print(datetime.now(), text) # 根据词汇表,将测试句子转为ids。 text_ids = q_vocabutil.get_ids_word(text) print(datetime.now(), text_ids) # 建立解码所需的计算图。 output_op = model.inference(text_ids) sess = tf.Session() saver = tf.train.Saver() saver.restore(sess, checkpoint_path) # 读取翻译结果。 output_ids = sess.run(output_op) print(datetime.now(), output_ids) output_text = a_vocabutil.get_text(output_ids) # 输出翻译结果。 print(datetime.now(), output_text) sess.close()
def get_answer(text_ids, checkpoint_path): # print("input ids", text_ids) tf.reset_default_graph() # 定义训练用的循环神经网络模型。 with tf.variable_scope("nmt_model", reuse=None): model = NMTModel() #0:00:00.050704from datetime import datetime # 建立解码所需的计算图。 t=datetime.now() output_op = model.inference(text_ids) print(datetime.now()-t) sess = tf.Session() saver = tf.train.Saver() saver.restore(sess, checkpoint_path) #0:00:01.142495 # 读取翻译结果。 output_ids = sess.run(output_op) # print("output ids:", output_ids) sess.close() return output_ids
def get_answer(text_ids, checkpoint_path): tf.reset_default_graph() with tf.variable_scope("nmt_model", reuse=None): model = NMTModel() output_op = model.inference(text_ids) sess = tf.Session() saver = tf.train.Saver() saver.restore(sess, checkpoint_path) output_ids = sess.run(output_op) sess.close() return output_ids
class TestModel(): def __init__(self, vocabfile, checkpoint_path): self.vocabutil = VocabUtil(vocabfile) tf.reset_default_graph() # 定义训练用的循环神经网络模型。 with tf.variable_scope("nmt_model", reuse=tf.AUTO_REUSE): self.model = NMTModel() # 建立解码所需的计算图。 text_ids = self.vocabutil.get_ids_word("你是谁") output_op = self.model.inference(text_ids) # self.saver = tf.train.import_meta_graph(checkpoint_path+".meta") self.sess = tf.Session() self.saver = tf.train.Saver() self.saver.restore(self.sess, checkpoint_path) # self.sess.run(tf.global_variables_initializer()) answer = self.vocabutil.get_text(self.sess.run(output_op)) print(answer) # print(self.predict("你是谁")) def close(self): self.sess.close() def predict(self, q): # tf.reset_default_graph() text_ids = self.vocabutil.get_ids_word(q) output_op = self.model.inference(text_ids) self.sess.run(output_op) answer = self.vocabutil.get_text(output_op) return answer