TypeError:无法将feed_dict键解释为张量,需要了解会话和图表

时间:2019-02-25 11:28:46

标签: python tensorflow keras

我是tensorflow的新手,并使用手机发布了此内容。我实际上希望会话能够继续运行,因此使用了以下编码方式。但是,在一个地方我可以看到Placeholder节点存在,但是出现错误,提示该节点不存在。我对正在使用的同一图表表示怀疑。

class Model(object):

    def __init__(self, model_path):
        self.sess = tf.Session()
        self.graph = tf.Graph()
        self.graph_def = tf.GraphDef()

        with open(model_path, "rb") as f:
            self.graph_def.ParseFromString(f.read())

        with tf.Graph().as_default() as self.graph:
            tf.import_graph_def(self.graph_def)

        self.input_operation = self.graph.get_operation_by_name('import/Placeholder')
        self.output_operation = self.graph.get_operation_by_name('import/final_result')

    def predict(self, images):
        dims_expander = tf.expand_dims(images, 0)
        resized = tf.image.resize_bilinear(dims_expander, [299, 299])
        normalized = tf.divide(tf.subtract(resized, [0]), [255]) 
        print(normalized)
        for op in self.graph.get_operations():
            print(op.name)
            results = self.sess.run(self.output_operation.outputs[0], {self.input_operation.outputs[0]: self.sess.run(normalized)})
        results = np.squeeze(results)
        top_k = results.argsort()[-5:][::-1]
        labels = ['1','0']
        print(labels[top_k[0]], results[top_k[0]])

然后制作一个对象。

model = Model('identification_model.pb').predict(img_from_openCV)

以下是输出错误,包括打印语句,该语句打印了第一个要导入的节点/占位符

Tensor("truediv_13:0", shape=(1, 299, 299, 3), dtype=float32)
import/Placeholder
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\client\session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
   1091             subfeed_t = self.graph.as_graph_element(
-> 1092                 subfeed, allow_tensor=True, allow_operation=False)
   1093           except Exception as e:

C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py in as_graph_element(self, obj, allow_tensor, allow_operation)
   3489     with self._lock:
-> 3490       return self._as_graph_element_locked(obj, allow_tensor, allow_operation)
   3491 

C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py in _as_graph_element_locked(self, obj, allow_tensor, allow_operation)
   3568       if obj.graph is not self:
-> 3569         raise ValueError("Tensor %s is not an element of this graph." % obj)
   3570       return obj

ValueError: Tensor Tensor("import/Placeholder:0", shape=(?, 299, 299, 3), dtype=float32) is not an element of this graph.

During handling of the above exception, another exception occurred:

TypeError                                 Traceback (most recent call last)

----> 1 model = Model('identification_model.pb').predict(img)


     32         for op in self.graph.get_operations():
     33             print(op.name)
---> 34             results = self.sess.run(self.output_operation.outputs[0], {self.input_operation.outputs[0]: self.sess.run(normalized)})
     35         results = np.squeeze(results)
     36         top_k = results.argsort()[-5:][::-1]

C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\client\session.py in run(self, fetches, feed_dict, options, run_metadata)
    927     try:
    928       result = self._run(None, fetches, feed_dict, options_ptr,
--> 929                          run_metadata_ptr)
    930       if run_metadata:
    931         proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\client\session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
   1093           except Exception as e:
   1094             raise TypeError(
-> 1095                 'Cannot interpret feed_dict key as Tensor: ' + e.args[0])
   1096 
   1097           if isinstance(subfeed_val, ops.Tensor):

TypeError: Cannot interpret feed_dict key as Tensor: Tensor Tensor("import/Placeholder:0", shape=(?, 299, 299, 3), dtype=float32) is not an element of this graph.

1 个答案:

答案 0 :(得分:0)

创建会话时,默认情况下将启动默认图形,该图形不包含您要查找的操作(它们全部在self.graph中)。您应该执行以下操作:

with tf.Session(self.graph) as sess:
    sess.run(...)

现在,sess将有权访问self.input_operationself.output_operation。在您的代码中,这意味着您应该在创建self.graph之后创建会话。顺便说一句,在大多数情况下,仅使用默认图形会更方便(完全是为了避免此类问题)。可能this post在这方面也会为您提供帮助。