0

I defined a typical siamese network architecture, to get encodings i used temp_model (VGG model with weight pretrained with triplet loss function), in below code, finally i trained model and saved to my disk as h5 file, but when i load model for prediction, i got an error (ValueError: Invalid input_shape argument [(None, 224, 224, 3), (None, 224, 224, 3), (None, 224, 224, 3)]: model has 1 tensor inputs.)

'''

left_input = Input(shape = (224, 224, 3))
right_input = Input(shape = (224, 224, 3))

# Generate the encodings (feature vectors) for the two images
encoded_l = temp_model([left_input,left_input,left_input])
encoded_r = temp_model([right_input,right_input,right_input])

# Add a customized layer to compute the absolute difference between the encodings 
L1_layer = Lambda(lambda tensors:K.abs(tensors[0] - tensors[1]))
L1_distance = L1_layer([encoded_l, encoded_r])

L1_distance = Dense(512,activation='relu')(L1_distance)
L1_distance = Dropout(0.2)(L1_distance)

L1_distance = Dense(10,activation='relu')(L1_distance)
L1_distance = Dropout(0.2)(L1_distance)

# Add a dense layer with a sigmoid unit to generate the similarity score
prediction = Dense(1,activation='sigmoid')(L1_distance)

# Connect the inputs with the outputs
siamese_net = Model(inputs=[left_input,right_input],outputs=prediction)

siamese_net.compile(loss='binary_crossentropy', optimizer="adam",
      metrics=['accuracy'])

siamese_net.summary()

# return the model
return siamese_net 

''' --------------------------------------------------------------------------- ValueError Traceback (most recent call last) in 1 #final_model = siamese_model() ----> 2 final_model = load_model("triplet_loss_function_vgg16_siamese_h100_128.h5")

/opt/anaconda3/lib/python3.7/site-packages/keras/engine/saving.py in load_model(filepath, custom_objects, compile)
    417     f = h5dict(filepath, 'r')
    418     try:
--> 419         model = _deserialize_model(f, custom_objects, compile)
    420     finally:
    421         if opened_new_file:

/opt/anaconda3/lib/python3.7/site-packages/keras/engine/saving.py in _deserialize_model(f, custom_objects, compile)
    223         raise ValueError('No model found in config.')
    224     model_config = json.loads(model_config.decode('utf-8'))
--> 225     model = model_from_config(model_config, custom_objects=custom_objects)
    226     model_weights_group = f['model_weights']
    227 

/opt/anaconda3/lib/python3.7/site-packages/keras/engine/saving.py in model_from_config(config, custom_objects)
    456                         '`Sequential.from_config(config)`?')
    457     from ..layers import deserialize
--> 458     return deserialize(config, custom_objects=custom_objects)
    459 
    460 

/opt/anaconda3/lib/python3.7/site-packages/keras/layers/__init__.py in deserialize(config, custom_objects)
     53                                     module_objects=globs,
     54                                     custom_objects=custom_objects,
---> 55                                     printable_module_name='layer')

/opt/anaconda3/lib/python3.7/site-packages/keras/utils/generic_utils.py in deserialize_keras_object(identifier, module_objects, custom_objects, printable_module_name)
    143                     config['config'],
    144                     custom_objects=dict(list(_GLOBAL_CUSTOM_OBJECTS.items()) +
--> 145                                         list(custom_objects.items())))
    146             with CustomObjectScope(custom_objects):
    147                 return cls.from_config(config['config'])

/opt/anaconda3/lib/python3.7/site-packages/keras/engine/network.py in from_config(cls, config, custom_objects)
   1030                 if layer in unprocessed_nodes:
   1031                     for node_data in unprocessed_nodes.pop(layer):
-> 1032                         process_node(layer, node_data)
   1033 
   1034         name = config.get('name')

/opt/anaconda3/lib/python3.7/site-packages/keras/engine/network.py in process_node(layer, node_data)
    989             # and building the layer if needed.
    990             if input_tensors:
--> 991                 layer(unpack_singleton(input_tensors), **kwargs)
    992 
    993         def process_layer(layer_data):

/opt/anaconda3/lib/python3.7/site-packages/keras/engine/base_layer.py in __call__(self, inputs, **kwargs)
    472             if all([s is not None
    473                     for s in to_list(input_shape)]):
--> 474                 output_shape = self.compute_output_shape(input_shape)
    475             else:
    476                 if isinstance(input_shape, list):

/opt/anaconda3/lib/python3.7/site-packages/keras/engine/network.py in compute_output_shape(self, input_shape)
    591             raise ValueError('Invalid input_shape argument ' +
    592                              str(input_shape) + ': model has ' +
--> 593                              str(len(self._input_layers)) + ' tensor inputs.')
    594 
    595         cache_key = ', '.join([str(x) for x in input_shapes])

ValueError: Invalid input_shape argument [(None, 224, 224, 3), (None, 224, 224, 3), (None, 224, 224, 3)]: model has 1 tensor inputs.

'''

'''

model_siamese = siamese_model()
from keras.callbacks import ModelCheckpoint

checkpoint = ModelCheckpoint('triplet_loss_function_vgg16_siamese_h512_10_128.h5', verbose=1, monitor='val_loss',save_best_only=True, mode='auto')

hist = model_siamese.fit_generator(generate_batch_siamese(batch_size=128, validation=False),epochs=1000, steps_per_epoch=int((total * 0.8) / 32), 
            validation_steps=int((total * 0.10) / 32),
            validation_data=generate_batch_siamese(batch_size=128, validation=True), callbacks=[checkpoint], use_multiprocessing=True)



final_model = load_model("triplet_loss_function_vgg16_siamese_h100_128.h5")

'''

4
  • Please add the full error messages, including full traceback Commented Mar 2, 2020 at 14:10
  • I've just added full traceback, pls let me know thoughts Commented Mar 2, 2020 at 14:18
  • Can you also include the code that produces the trained model? Including both training and saving, and the imports used for that. Commented Mar 2, 2020 at 14:39
  • sure, added the remaining code Commented Mar 2, 2020 at 15:59

2 Answers 2

0

Try changing the code section for encoding generation to

# Generate the encodings (feature vectors) for the two images
encoded_l = temp_model(left_input)
encoded_r = temp_model(right_input)
Sign up to request clarification or add additional context in comments.

5 Comments

this will not work, to get an embedding of an image, this model need, Anchor, positive, negative tensors. Also, i already trained my model, problem is while loading model using keras
Can you put up the traceback?
@DeepakKumar The error says that the model has only one input tensor, so its not clear why you think it would not work.
I've added traceback, kindly check
please note this error came up while loading model from disk, when i was training this model, there was no issue
0

This is a common problem while loading nested models, there's no single answer to this problem, but there're some useful links where you can get hints to solve such issues. https://github.com/keras-team/keras/pull/11847

In my case, i re-defined an architecture (same as my training), set trainable parameters to false and than instead of using load_model i used load_weights and it worked for me. As i said, there's no single answer, you've to test and try different options.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.