无法使用 tf.train.import_meta_graph 导入元图,名称“”指的是不在图中的操作

Unable to import meta graph using tf.train.import_meta_graph, The name '' refers to an Operation not in the graph

OS Platform and Distribution: Ubuntu 18.04

tf.VERSION = 1.13.1                                                            
tf.GIT_VERSION = b'v1.13.1-0-g6612da8951'                                      
tf.COMPILER_VERSION = b'v1.13.1-0-g6612da8951'
Python version: 3.6.10
GCC/Compiler version (if compiling from source): 4.8.5
CUDA/cuDNN version: 10.2
GPU model and memory: Nvidia Tesla V100, 16gb

我无法导入元图。 即使我定义 tf.placeholder(name="data", shape=(None,64), dtype=tf.float32),下一层也会出错。 我也尝试使用 tf2.0。但同样的问题。

重现问题的代码

import tensorflow as tf

model_dir="./model"   # change this line to the directory where checkpoint and models are saved
checkpoint = tf.train.get_checkpoint_state(model_dir)
input_checkpoint = checkpoint.model_checkpoint_path
clear_devices = True

with tf.Session(graph=tf.Graph()) as sess:
    saver = tf.train.import_meta_graph(input_checkpoint + '.meta', clear_devices=clear_devices)

检查点文件附加在 model.zip 中。

堆栈跟踪

Traceback (most recent call last):
  File "import_meta_graph.py", line 11, in <module>
    saver = tf.train.import_meta_graph(input_checkpoint + '.meta', clear_devices=clear_devices)
  File "/home/ubuntu/tf1.13/lib/python3.6/site-packages/tensorflow/python/training/saver.py", line 1435, in import_meta_graph
    meta_graph_or_file, clear_devices, import_scope, **kwargs)[0]
  File "/home/ubuntu/tf1.13/lib/python3.6/site-packages/tensorflow/python/training/saver.py", line 1457, in _import_meta_graph_with_return_elements
    **kwargs))
  File "/home/ubuntu/tf1.13/lib/python3.6/site-packages/tensorflow/python/framework/meta_graph.py", line 852, in import_scoped_meta_graph_with_return_elements
    ops.prepend_name_scope(value, scope_to_prepend_to_names))
  File "/home/ubuntu/tf1.13/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 3478, in as_graph_element
    return self._as_graph_element_locked(obj, allow_tensor, allow_operation)
  File "/home/ubuntu/tf1.13/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 3538, in _as_graph_element_locked
    "graph." % repr(name))
KeyError: "The name 'data' refers to an Operation not in the graph."

您应该删除 graph=tf.Graph(),否则 import_meta_graph 会将其导入错误的图表。