【问题标题】:Getting Error: while loading model in Keras:出现错误:在 Keras 中加载模型时:
【发布时间】:2020-03-02 13:26:30
【问题描述】:

我定义了一个典型的连体网络架构,为了获得编码,我使用了 temp_model(具有三重损失函数的权重预训练的 VGG 模型),在下面的代码中,最后我训练了模型并作为 h5 文件保存到我的磁盘,但是当我加载用于预测的模型,我得到一个错误(ValueError: Invalid input_shape argument [(None, 224, 224, 3), (None, 224, 224, 3), (None, 224, 224, 3)]:模型有 1 个张量输入。)

'''

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(最近一次调用最后一次) 在 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")

'''

【问题讨论】:

  • 请添加完整的错误信息,包括完整的回溯
  • 我刚刚添加了完整的回溯,请告诉我想法
  • 能否也包含生成训练模型的代码?包括训练和保存,以及用于此的导入。
  • 确定,添加剩余代码

标签: python keras deep-learning


【解决方案1】:

尝试将用于编码生成的代码部分更改为

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

【讨论】:

  • 这行不通,要获得图像的嵌入,此模型需要 Anchor、正张量、负张量。另外,我已经训练了我的模型,问题是使用 keras 加载模型时
  • 你能把traceback放上来吗?
  • @DeepakKumar 错误说模型只有一个输入张量,所以不清楚你为什么认为它不起作用。
  • 我添加了traceback,请检查
  • 请注意这个错误是从磁盘加载模型时出现的,当我训练这个模型时,没有问题
【解决方案2】:

这是加载嵌套模型时的常见问题,这个问题没有单一的答案,但有一些有用的链接可以让您获得解决此类问题的提示。 https://github.com/keras-team/keras/pull/11847

在我的例子中,我重新定义了一个架构(与我的训练相同),将可训练参数设置为 false,而不是使用 load_model,我使用了 load_weights,它对我有用。正如我所说,没有单一的答案,您必须测试并尝试不同的选项。

【讨论】:

    猜你喜欢
    • 2019-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-26
    • 2020-01-08
    • 2019-07-29
    • 1970-01-01
    相关资源
    最近更新 更多