没有上下文管理器,Tensorflow模型不会恢复

时间:2018-02-14 11:03:19

标签: tensorflow

我有一个训练有素的模型,我将其命名为best_model

所以在我目前的工作目录中,我有:

  • best_model.ckpt.data-00000-of-00001
  • best_model.ckpt.index
  • best_model.ckpt.meta
  • checkpoint

现在,如果我尝试通过以下代码段加载,它会加载并完美地提供结果。

checkpoint = "./best_model.ckpt"

loaded_graph = train_graph
with tf.Session(graph=loaded_graph) as sess:
    # Load saved model
    loader = tf.train.import_meta_graph(checkpoint + '.meta')
    loader.restore(sess, checkpoint)

    # some code for inference

如果我想多次进行推理怎么办?我不想每次都加载模型。所以我决定将推理代码放在一个函数中,我将单独加载模型。

但以下代码段不起作用

checkpoint = "./best_model.ckpt"

loaded_graph = train_graph
sess = tf.Session(graph=loaded_graph)
loader = tf.train.import_meta_graph(checkpoint + '.meta')
loader.restore(sess, checkpoint)

def inference(text):
    # some code

以下是Traceback

INFO:tensorflow:Restoring parameters from ./best_model.ckpt
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-58-1947eb6ae173> in <module>()
     12 checkpoint = "./best_model.ckpt"
     13 loader = tf.train.import_meta_graph(checkpoint + '.meta')
---> 14 loader.restore(sess, checkpoint)
     15 
     16 #sess = gen_sess()

C:\Program Files\Anaconda3\lib\site-packages\tensorflow\python\training\saver.py in restore(self, sess, save_path)
   1455     logging.info("Restoring parameters from %s", save_path)
   1456     sess.run(self.saver_def.restore_op_name,
-> 1457              {self.saver_def.filename_tensor_name: save_path})
   1458 
   1459   @staticmethod

C:\Program Files\Anaconda3\lib\site-packages\tensorflow\python\client\session.py in run(self, fetches, feed_dict, options, run_metadata)
    776     try:
    777       result = self._run(None, fetches, feed_dict, options_ptr,
--> 778                          run_metadata_ptr)
    779       if run_metadata:
    780         proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

C:\Program Files\Anaconda3\lib\site-packages\tensorflow\python\client\session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
    914       raise RuntimeError('Attempted to use a closed Session.')
    915     if self.graph.version == 0:
--> 916       raise RuntimeError('The Session graph is empty.  Add operations to the '
    917                          'graph before calling run().')
    918 

RuntimeError: The Session graph is empty.  Add operations to the graph before calling run().

我正在使用tensorflow 1.1.0,因为我正在使用旧的github代码进行尝试。我是张力流的新手,我不知道我是否遗漏了一些明显的概念。任何帮助将不胜感激。

0 个答案:

没有答案