ValueError:Tensor Tensor(“ dense_1 / Sigmoid:0”,shape =(?, 1),dtype = float32)不是此图的元素

时间:2019-06-09 02:17:15

标签: tensorflow keras tf.keras

我正在使用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()

我希望代码不会崩溃

4 个答案:

答案 0 :(得分:0)

我认为您应该添加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()

答案 1 :(得分:0)

最后,我不知道发生了什么,我不知道这是否是由于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

答案 2 :(得分:0)

我遇到了同样的问题,但是上面的解决方案对我而言并不可行。我想订阅一张图片并使用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)

希望上述解决方案不能解决问题。

答案 3 :(得分:0)

我正在订阅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,Ubuntu 18.04