【问题标题】:Loading a keras model with custom loss based on input根据输入加载具有自定义损失的 keras 模型
【发布时间】:2020-04-30 22:12:41
【问题描述】:

我有一个自定义损失,它使用模型的一个输入。

def closs(labels,latent_dim):
  def loss(y_true,y_pred):
    return metric_learning.contrastive_loss(labels=labels,
                        embeddings_anchor=y_pred[:,:latent_dim],
                        embeddings_positive=y_pred[:,latent_dim:])
return loss

其中标签是模型的输入。模型架构为:

def build_model():
  left_input = Input(shape=(2900,1))
  right_input = Input(shape=(2900,1))
  label = Input(shape=(1,))

  encoder = build_encoder()

  left_embed = encoder(left_input)
  right_embed = encoder(right_input)

  embeds = Concatenate()([left_embed,right_embed])

  model = Model(inputs=[left_input,right_input,label],outputs=[embeds])
  return model, label

然后我使用返回的“标签”来编译模型:

model,label = build_model()
model.compile(optimizer='adam',loss=closs(label,256))

但是当我尝试加载模型时,我必须将此损失作为 custom_object 传递,所以是这样的:

model = load_model('model/cl_model.h5',custom_objects={'loss':closs(xyz,256)})

问题是我在不同的 python 脚本中加载模型,所以我没有“标签”输入对象。 我该如何克服这个问题?

【问题讨论】:

    标签: python keras neural-network conv-neural-network keras-layer


    【解决方案1】:

    您是在使用权重来重新训练模型还是只是为了预测新数据? 在仅预测的情况下,您可以使用

    model.load_weights('model/cl_model.h5') 
    

    定义模型后,您不必传递损失函数,因为它仅用于预测。

    【讨论】:

    • 我想重新训练模型
    猜你喜欢
    • 1970-01-01
    • 2018-06-30
    • 2019-07-06
    • 2019-05-27
    • 2020-05-14
    • 2023-03-14
    • 2020-08-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多