会话结束时启动模型 - Tensorflow

时间:2017-10-10 14:19:25

标签: python-3.x tensorflow neural-network save

我构建了一个带有两个隐藏层的神经网络。当我启动会话时,我通过以下方式保存会话:

saver.save(sess, "model.ckpt")

如果我仍在同一会话中并启动此代码:

restorer=tf.train.Saver()
with tf.Session() as sess:
    restorer.restore(sess,"./prova")
    new_graph = tf.train.import_meta_graph('prova.meta') 
    new_graph.restore(sess, 'prova.ckpt')
    feed={
        pred1.inputs:test_data,
        pred1.is_training:False
    }
    test_predict=sess.run(pred1.predicted,feed_dict=feed)

我可以启动测试模型。

问题是:会话结束时有一种启动模型的方法吗?特别是,我把我的火车结果保存在.ckpt,我可以在另一个时刻重新启动模型吗?

1 个答案:

答案 0 :(得分:0)

您无法在tf.Session之外运行模型。来自the documentation的引用:

  

Session对象封装了执行Operation对象的环境,并评估了Tensor对象。

但您可以轻松地多次打开和关闭会话,使用现有图表或加载以前保存的图表,并在新会话中使用它。这是一个略微修改的example from the doc

import tensorflow as tf

v1 = tf.get_variable("v1", shape=[3], initializer = tf.zeros_initializer)
v2 = tf.get_variable("v2", shape=[5], initializer = tf.zeros_initializer)

inc_v1 = v1.assign(v1+1)
dec_v2 = v2.assign(v2-1)
init_op = tf.global_variables_initializer()
saver = tf.train.Saver()

with tf.Session() as sess:
  sess.run(init_op)
  inc_v1.op.run()
  dec_v2.op.run()
  save_path = saver.save(sess, "/tmp/model.ckpt")
  print("Model saved in file: %s" % save_path)

with tf.Session() as sess:
  saver.restore(sess, "/tmp/model.ckpt")
  print("Model restored.")
  print("v1 : %s" % v1.eval())
  print("v2 : %s" % v2.eval())

在这两个会话之间,您无法评估v1v2,但您可以在开始新会话后立即进行评估。