Keras model.predict()在load_model()之后引发ValueError

时间:2018-01-16 00:10:38

标签: python tensorflow keras

我正在尝试加载多个已保存的keras模型,并在我的进程的单独线程中使用它们。我把每个模型都放在字典中但是当我打电话给model.predict(data)时,我得到以下内容:

hub: uncaught exception: Traceback (most recent call last):
File "/home/mininet/ryu/ryu/lib/hub.py", line 59, in _launch
return func(*args, **kwargs)
File "/home/mininet/ryu/ryu/app/testSwitch.py", line 230, in predictor
self.predict('r1', '172.168.3.2', cnt)
File "/home/mininet/ryu/ryu/app/testSwitch.py", line 249, in predict
predictions = model.predict(counter)
File "build/bdist.linux-x86_64/egg/keras/models.py", line 1027, in predict
steps=steps)
File "build/bdist.linux-x86_64/egg/keras/engine/training.py", line 1797, in predict
self._make_predict_function()
File "build/bdist.linux-x86_64/egg/keras/engine/training.py", line 1009, in _make_predict_function
**kwargs)
File "build/bdist.linux-x86_64/egg/keras/backend/tensorflow_backend.py", line 2499, in function
return Function(inputs, outputs, updates=updates, **kwargs)
File "build/bdist.linux-x86_64/egg/keras/backend/tensorflow_backend.py", line 2442, in __init__
with tf.control_dependencies(self.outputs):
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 4304, in control_dependencies
return get_default_graph().control_dependencies(control_inputs)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 4017, in control_dependencies
c = self.as_graph_element(c)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 3035, in as_graph_element
return self._as_graph_element_locked(obj, allow_tensor, allow_operation)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 3114, in _as_graph_element_locked
raise ValueError("Tensor %s is not an element of this graph." % obj)
ValueError: Tensor Tensor("dense_4/Sigmoid:0", shape=(?, 10), dtype=float32) is not an element of this graph.

我按照建议here加载模型后尝试调用model._make_predict_function(),但它没有帮助。

[编辑] 问题可能与多线程有关,我尝试在单个过程中加载和使用多个模型,并且它可以顺利运行。 这是我使用keras的代码部分

from ryu.lib import hub
from ryu.base import app_manager

class MyClass(app_manager.RyuApp):
    def __init__(self, *args, **kargs):
        ....
        self.load_models()
        self.predic_th = hub.spawn(self.predictor)
        self.another_th = hub.spawn(self.another)
        ....
    def load_models(self):
        target = [t for t in directory]
        self.models = {t:self.get_model(t) for in in target}

    def get_model(self, target):
        model = load_model('{:}_model.h5'.format(target))
        model._make_predict_function()
        return model

    def predictor(self,data, target):
        model = self.models[target]
        while True:
            model.predict(data)
            hub.sleep(2)

0 个答案:

没有答案