ValueError: Tensor Tensor("dense_1/Sigmoid:0", shape=(?, 1), dtype=float32) is not an element of this graph

ValueError: Tensor Tensor("dense_1/Sigmoid:0", shape=(?, 1), dtype=float32) is not an element of this graph

我正在使用 tf.keras 加载我之前使用 tf.keras 制作的模型,但是当我尝试进行预测时,我得到了这个

[ERROR] [1560045312.143498]: bad callback: <function callback at 0x7f16fe94b8c0>
Traceback (most recent call last):
  File "/opt/ros/kinetic/lib64/python2.7/site-packages/rospy/topics.py", line 750, in _invoke_callback
    cb(msg)
  File "/home/franky/catkin_ws_kinetic/src/tfm/scripts/nnet_predictor.py", line 50, in callback
    true_face.eyes[1].height
  File "/usr/lib64/python2.7/site-packages/tensorflow/python/keras/engine/training.py", line 1113, in predict
    self, x, batch_size=batch_size, verbose=verbose, steps=steps)
  File "/usr/lib64/python2.7/site-packages/tensorflow/python/keras/engine/training_arrays.py", line 195, in model_iteration
    f = _make_execution_function(model, mode)
  File "/usr/lib64/python2.7/site-packages/tensorflow/python/keras/engine/training_arrays.py", line 122, in _make_execution_function
    return model._make_execution_function(mode)
  File "/usr/lib64/python2.7/site-packages/tensorflow/python/keras/engine/training.py", line 1989, in _make_execution_function
    self._make_predict_function()
  File "/usr/lib64/python2.7/site-packages/tensorflow/python/keras/engine/training.py", line 1979, in _make_predict_function
    **kwargs)
  File "/usr/lib64/python2.7/site-packages/tensorflow/python/keras/backend.py", line 3201, in function
    return GraphExecutionFunction(inputs, outputs, updates=updates, **kwargs)
  File "/usr/lib64/python2.7/site-packages/tensorflow/python/keras/backend.py", line 2939, in __init__
    with ops.control_dependencies(self.outputs):
  File "/usr/lib64/python2.7/site-packages/tensorflow/python/framework/ops.py", line 5028, in control_dependencies
    return get_default_graph().control_dependencies(control_inputs)
  File "/usr/lib64/python2.7/site-packages/tensorflow/python/framework/ops.py", line 4528, in control_dependencies
    c = self.as_graph_element(c)
  File "/usr/lib64/python2.7/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 "/usr/lib64/python2.7/site-packages/tensorflow/python/framework/ops.py", line 3557, in _as_graph_element_locked
    raise ValueError("Tensor %s is not an element of this graph." % obj)
ValueError: Tensor Tensor("dense_1/Sigmoid:0", shape=(?, 1), dtype=float32) is not an element of this graph.

我也可能会说我在ros框架中使用这个(机器人操作系统[它不是操作系统,只是有一个超级误导的名字,我在linux])所以我知道callback() 正在一个线程中被调用,我无法避免使用 ros。

我也测试过,如果我在主线程中使用预测功能,一切正常。

我已经尝试了 with graph.as_default():clear_session() 解决方案,但没有成功。

我已经检查过每个导入都来自 tf.keras 并且我没有将 tf.keras 与 keras

混用

我还尝试使用 Lock() 来避免同时调用 predict() 函数 2+

#!/usr/bin/python2
from tensorflow import keras
from tensorflow.keras.models import model_from_json
from tfm_msgs.msg import IsLooking
import numpy as np
from tensorflow.keras.backend import clear_session
import tensorflow as tf
from threading import Thread, Lock
# other non relevant imports

def callback(face_array_stamped):
    global mutex
    mutex.acquire()
    try:
        global graph
        # with graph.as_default():
        global my_model
        global pub
        true_faces = []
        for face in face_array_stamped.faces:
            if len(face.eyes) == 2:
                true_faces.append(face)
        if len(true_faces) == 1:
            true_face = true_faces[0]
            prediction = my_model.predict(np.array([[
                #all the data here
                                        ]]))[0]
            #↑↑↑↑↑It crashes here↑↑↑↑↑↑
            #more non relevant stuff
    finally:
        mutex.release()

if __name__ == '__main__':
    # clear_session()
    model_dir = str(os.path.dirname(os.path.abspath(__file__))) + "/../nnet_models/"
    json_file = open(model_dir+'model.json', 'r')
    my_model = model_from_json(json_file.read())
    json_file.close()
    my_model.load_weights(model_dir+'model.h5')
    # my_model._make_predict_function()
    my_model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
    # my_model.summary()

我希望代码不会崩溃

我认为你应该添加 graph = tf.get_default_graph()with graph.as_default():

这个呢?

from tensorflow import keras
from tensorflow.keras.models import model_from_json
from tfm_msgs.msg import IsLooking
import numpy as np
from tensorflow.keras.backend import clear_session
import tensorflow as tf
from threading import Thread, Lock
# other non relevant imports


graph = tf.get_default_graph()


def callback(face_array_stamped):
    global mutex
    mutex.acquire()
    try:
        global my_model
        global pub
        true_faces = []
        for face in face_array_stamped.faces:
            if len(face.eyes) == 2:
                true_faces.append(face)
        if len(true_faces) == 1:
            true_face = true_faces[0]
            with graph.as_default():
                prediction = my_model.predict(np.array([[
                #all the data here
                                        ]]))[0]
            #↑↑↑↑↑It crashes here↑↑↑↑↑↑
            #more non relevant stuff
    finally:
        mutex.release()

if __name__ == '__main__':
    # clear_session()
    model_dir = str(os.path.dirname(os.path.abspath(__file__))) + "/../nnet_models/"
    json_file = open(model_dir+'model.json', 'r')
    my_model = model_from_json(json_file.read())
    json_file.close()
    my_model.load_weights(model_dir+'model.h5')
    # my_model._make_predict_function()
    my_model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
    # my_model.summary()

最后我搞不清楚是怎么回事,不知道是不是因为ros的工作原理,但我最终还是使用了解决方案 Execute Python function in Main thread from call in Dummy thread 所以我的代码最终是这样的:

callback_queue = Queue.Queue()


def prediction_callback(true_face, face_header):
    #non relevant stuff
    prediction = my_model.predict(np.array([[
        #all the variables
        ]])
    #more non relevant stuff


def face_callback(face_array_stamped): #this is the original callback
    #...
    callback_queue.put(lambda: prediction_callback(true_face, face_array_stamped.header))
    #...


if __name__ == '__main__':
    #...
    while not rospy.is_shutdown():
        try:
            callback_queue.get(True, 2)()
        except Queue.Empty:
            pass

我遇到了同样的问题,但上面的解决方案对我没有用。我想订阅一张图片并用 keras/tensorflow 预测一些东西。这样做,我遇到了上述相同的错误。

以下解决方案对我有用:

def method_to_predict(msg):
    # ...
    model.predict(...)
    # ...

if __name__ == '__main__':
    rospy.init_node('my_node', anonymous=False)

    while not rospy.is_shutdown():
        msg = rospy.wait_for_message('topic', msg_type)
        method_to_predict(msg)

如果上述解决方案不起作用,希望这对您有所帮助。

我正在 ROS 和回调方法调用中订阅一个主题 model.predict()。添加:

import tensorflow as tf

global graph,model
graph = tf.get_default_graph()

with graph.as_default():
            steering_angle = float(model.predict(cropped[None, :, :, :], batch_size=1))

回调解决了我的问题,正如 Nattaphon 所建议的那样。

Tensorflow 1.12,Keras 2.0.6,Ubuntu18.04