Klausstaler
Klausstaler

Reputation: 41

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

I am currently trying to use the first 50 layers of the MobileNetV2. Therefore, I want to extract those layers and create a new model.

I thought I could just call every layer, but the "block_2_add" layer causes an error and I don't understand why.

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.

Upvotes: 1

Views: 9631

Answers (2)

Fakhreddine
Fakhreddine

Reputation: 31

I may be late but I guess this following code will do it for you

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
                         )

Upvotes: 3

Addy
Addy

Reputation: 1450

My guess is that the MobileNetV2 is not a sequential model, i.e. the layers graph is not linear. If you want just the output of the model and not any intermediate layer outputs, I think following code should do the job (even though it seems that you want to compute the last layer before output, the result still should be what you want):

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)

Upvotes: 3

Related Questions