【问题标题】:ValueError: A merge layer should be called on a list of inputs. Tensorflow KerasValueError:应在输入列表上调用合并层。 TensorFlow Keras
【发布时间】:2019-06-26 11:14:33
【问题描述】:

我目前正在尝试使用 MobileNetV2 的前 50 层。因此,我想提取这些层并创建一个新模型。

我以为我可以只调用每一层,但是“block_2_add”层会导致错误,我不明白为什么。

import tensorflow as tf
from keras.models import Model

mobile_net=tf.keras.applications.mobilenet_v2.MobileNetV2(input_shape=(224,224,3), alpha=0.5, include_top=False, weights='imagenet')


inputs = Input(shape=(224, 224, 3))
x=mobile_net.layers[1](inputs)
for layer in mobile_net.layers[2:50]:
  x=layer(x)




{'name': 'block_2_add', 'trainable': True, 'dtype': 'float32'}
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-77-5873b9344fa3> in <module>()
      3 for layer in mobile_net.layers[2:50]:
      4   print(layer.get_config())
----> 5   x=layer(x)
      6 
      7 for layer in mobile_net.layers[:50]:

1 frames
/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/layers/merge.py in call(self, inputs)
    119   def call(self, inputs):
    120     if not isinstance(inputs, list):
--> 121       raise ValueError('A merge layer should be called on a list of inputs.')
    122     if self._reshape_required:
    123       reshaped_inputs = []

ValueError: A merge layer should be called on a list of inputs.

【问题讨论】:

    标签: python-3.x tensorflow keras-layer tf.keras


    【解决方案1】:

    我的猜测是 MobileNetV2 不是顺序模型,即层图不是线性的。如果您只想要模型的输出而不想要任何中间层输出,我认为下面的代码应该可以完成这项工作(即使您似乎想在输出之前计算最后一层,结果仍然应该是您想要的):

    import tensorflow as tf
    from keras.models import Model
    
    mobile_net=tf.keras.applications.mobilenet_v2.MobileNetV2(input_shape=(224,224,3), alpha=0.5, include_top=False, weights='imagenet')
    
    
    inputs = Input(shape=(224, 224, 3))
    output = mobile_net(inputs)
    

    【讨论】:

    • 是的,它不是顺序模型,请参阅:github.com/keras-team/keras-applications/blob/master/…
    • 没错,但由于我的新数据集非常小,我只需要神经网络的最后几层。你知道我如何提取这些吗?
    • 我认为您已经通过设置include_top=False 来提取它,如果您调用mobile_net(inputs),您可能会因为该标志而获得最后一层的输出。检查我的代码的形状,如果它与原始网络输出或最后一层相匹配,那应该会告诉你你得到的是哪一层。
    • 我的意思是我只想要第一个,比如说50层的mobilenet。我想丢弃完全连接的层以及之前的一些层。我该怎么做?
    • 我知道已经很久了,但我想知道您是否有答案?因为我想做同样的事情,目前面临同样的问题。
    【解决方案2】:

    我可能会迟到,但我想下面的代码会为你做的

    pre_trained_model = MobileNetV2(input_shape = (256, 256, 3), 
                                include_top = False, 
                                weights = "imagenet" )
    last_layer = pre_trained_model.get_layer('block_15_project_BN'#the name of the last layer you want from the model)
    last_output = last_layer.output
    input_l = pre_trained_model.input
    base_model1 = tf.keras.Model(input_l, last_output
                             )
    

    【讨论】:

      猜你喜欢
      • 2020-05-14
      • 1970-01-01
      • 2020-04-25
      • 2019-07-31
      • 2018-09-06
      • 1970-01-01
      • 1970-01-01
      • 2017-11-19
      • 1970-01-01
      相关资源
      最近更新 更多