首页 > 解决方案 > ValueError:在创建预训练模型的集合时,模型的输出张量必须是 Keras `Layer` 的输出

问题描述

我有一些预训练的二进制 Keras 模型。本例中的 3 个模型。我试图通过平均这些模型的预测来制作一个集成模型。为此,我从集成模型中参考此处的示例。我的代码如下

models=list()
for i in os.listdir(model_root):  # to get all the models in one list
    print(i)
    filename = model_root + "/" + i
    model = load_model(filename, custom_objects={'KerasLayer': hub.KerasLayer})  # load model
    models.append(model)
# ensemble prediction
print(len(models))
yhats = [model.predict(image_data_val) for model in models]
print(np.array(yhats).shape)               # (3, 32, 2)
outputs = layers.average(yhats)     # averaging the model output
ensemble_model = keras.models.Model(inputs=keras.Input(shape=(None,224,224,3)), outputs=outputs)

我收到以下错误

Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "C:\Program Files\JetBrains\PyCharm 2019.2\helpers\pydev\_pydev_bundle\pydev_umd.py", line 197, in runfile
    pydev_imports.execfile(filename, global_vars, local_vars)  # execute the script
  File "C:\Program Files\JetBrains\PyCharm 2019.2\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "C:/Users/Pawandeep/Desktop/Python projects/ensemble_image.py", line 68, in <module>
    ensemble_model = keras.models.Model(inputs=keras.Input(shape=(None,224,224,3)), outputs=outputs)
  File "C:\Python\lib\site-packages\keras\legacy\interfaces.py", line 91, in wrapper
    return func(*args, **kwargs)
  File "C:\Python\lib\site-packages\keras\engine\network.py", line 93, in __init__
    self._init_graph_network(*args, **kwargs)
  File "C:\Python\lib\site-packages\keras\engine\network.py", line 188, in _init_graph_network
    'Found: ' + str(x))
ValueError: Output tensors to a Model must be the output of a Keras `Layer` (thus holding past layer metadata). Found: Tensor("average/truediv:0", shape=(32, 2), dtype=float32)

所以总体目标是集成在 sigmoid 函数上训练的二元 keras 模型。我无法正确理解错误,因为输出是 keras 模型本身的输出。

根据建议重新定义模型后的回溯

W0819 16:51:11.051734 11788 ag_logging.py:145] Entity <tensorflow.python.saved_model.function_deserialization.RestoredFunction object at 0x0000020A66459710> could not be transformed and will be executed as-is. Please report this to the AutgoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Could not find matching function to call loaded from the SavedModel. Got:
  Positional arguments (3 total):
    * Tensor("inputs:0", shape=(?, ?, 224, 224, 3), dtype=float32)
    * False
    * 0.99
  Keyword arguments: {}
Expected these arguments to match one of the following 2 option(s):
Option 1:
  Positional arguments (3 total):
    * TensorSpec(shape=(?, 224, 224, 3), dtype=tf.float32, name='inputs')
    * True
    * TensorSpec(shape=(), dtype=tf.float32, name='batch_norm_momentum')
  Keyword arguments: {}
Option 2:
  Positional arguments (3 total):
    * TensorSpec(shape=(?, 224, 224, 3), dtype=tf.float32, name='inputs')
    * False
    * TensorSpec(shape=(), dtype=tf.float32, name='batch_norm_momentum')
  Keyword arguments: {}
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "C:\Program Files\JetBrains\PyCharm 2019.2\helpers\pydev\_pydev_bundle\pydev_umd.py", line 197, in runfile
    pydev_imports.execfile(filename, global_vars, local_vars)  # execute the script
  File "C:\Program Files\JetBrains\PyCharm 2019.2\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "C:/Users/Pawandeep/Desktop/Python projects/ensemble_image.py", line 66, in <module>
    yhats = [model(inputs) for model in models]
  File "C:/Users/Pawandeep/Desktop/Python projects/ensemble_image.py", line 66, in <listcomp>
    yhats = [model(inputs) for model in models]
  File "C:\Python\lib\site-packages\tensorflow\python\keras\engine\base_layer.py", line 634, in __call__
    outputs = call_fn(inputs, *args, **kwargs)
  File "C:\Python\lib\site-packages\tensorflow\python\keras\engine\sequential.py", line 247, in call
    return super(Sequential, self).call(inputs, training=training, mask=mask)
  File "C:\Python\lib\site-packages\tensorflow\python\keras\engine\network.py", line 751, in call
    return self._run_internal_graph(inputs, training=training, mask=mask)
  File "C:\Python\lib\site-packages\tensorflow\python\keras\engine\network.py", line 893, in _run_internal_graph
    output_tensors = layer(computed_tensors, **kwargs)
  File "C:\Python\lib\site-packages\tensorflow\python\keras\engine\base_layer.py", line 634, in __call__
    outputs = call_fn(inputs, *args, **kwargs)
  File "C:\Python\lib\site-packages\tensorflow\python\keras\engine\sequential.py", line 247, in call
    return super(Sequential, self).call(inputs, training=training, mask=mask)
  File "C:\Python\lib\site-packages\tensorflow\python\keras\engine\network.py", line 751, in call
    return self._run_internal_graph(inputs, training=training, mask=mask)
  File "C:\Python\lib\site-packages\tensorflow\python\keras\engine\network.py", line 893, in _run_internal_graph
    output_tensors = layer(computed_tensors, **kwargs)
  File "C:\Python\lib\site-packages\tensorflow\python\keras\engine\base_layer.py", line 634, in __call__
    outputs = call_fn(inputs, *args, **kwargs)
  File "C:\Python\lib\site-packages\tensorflow\python\autograph\impl\api.py", line 149, in wrapper
    raise e.ag_error_metadata.to_exception(type(e))
ValueError: in converted code:
    relative to C:\Python\lib\site-packages:
    tensorflow_hub\keras_layer.py:173 call *
        result = smart_cond.smart_cond(training,
    tensorflow\python\framework\smart_cond.py:56 smart_cond
        return false_fn()
    tensorflow\python\saved_model\load.py:323 _call_attribute
        return instance.__call__(*args, **kwargs)
    tensorflow\python\eager\def_function.py:406 __call__
        results = self._stateful_fn(*args, **kwds)
    tensorflow\python\eager\function.py:1323 __call__
        graph_function, args, kwargs = self._maybe_define_function(args, kwargs)
    tensorflow\python\eager\function.py:1652 _maybe_define_function
        graph_function = self._create_graph_function(args, kwargs)
    tensorflow\python\eager\function.py:1545 _create_graph_function
        capture_by_value=self._capture_by_value),
    tensorflow\python\framework\func_graph.py:715 func_graph_from_py_func
        func_outputs = python_func(*func_args, **func_kwargs)
    tensorflow\python\eager\def_function.py:307 wrapped_fn
        return weak_wrapped_fn().__wrapped__(*args, **kwds)
    tensorflow\python\saved_model\function_deserialization.py:256 restored_function_body
        "\n\n".join(signature_descriptions)))
    ValueError: Could not find matching function to call loaded from the SavedModel. Got:
      Positional arguments (3 total):
        * Tensor("inputs:0", shape=(?, ?, 224, 224, 3), dtype=float32)
        * False
        * 0.99
      Keyword arguments: {}

    Expected these arguments to match one of the following 2 option(s):

    Option 1:
      Positional arguments (3 total):
        * TensorSpec(shape=(?, 224, 224, 3), dtype=tf.float32, name='inputs')
        * True
        * TensorSpec(shape=(), dtype=tf.float32, name='batch_norm_momentum')
      Keyword arguments: {}

    Option 2:
      Positional arguments (3 total):
        * TensorSpec(shape=(?, 224, 224, 3), dtype=tf.float32, name='inputs')
        * False
        * TensorSpec(shape=(), dtype=tf.float32, name='batch_norm_momentum')
      Keyword arguments: {}

标签: python-3.xtensorflowkeras

解决方案



推荐阅读