tensorflow2.3+ kears tf.keras.models.load_model载人模型,模型ValueError: Unknown loss function: define_loss

自定义损失函数载入模型失效解决方案

def sum_loss(inputs):
    ctr_true, ctr_pred, ctcvr_true, ctcvr_pred = inputs
    ctr_loss = tf.keras.losses.binary_crossentropy(y_true=ctr_true, y_pred=ctr_pred)
    ctcvr_loss = tf.keras.losses.binary_crossentropy(y_true=ctcvr_true, y_pred=ctcvr_pred)
    loss = ctr_loss + ctcvr_loss
    return loss
def define_loss(y_true, y_pred):
    return tf.math.reduce_mean(y_pred)
loss = [tf.keras.losses.BinaryCrossentropy(),
           tf.keras.losses.BinaryCrossentropy(),define_loss]
            metrics = {'a': tf.keras.metrics.AUC(),
               'b': tf.keras.metrics.AUC()}

model = tf.keras.Model(inputs=inputs,
                           outputs=outputs,
                           name="model")

1. 方案一,采用custom_objects定义出来

t=tf.keras.models.load_model(f'{model_path}',custom_objects={'define_loss':define_loss})

2、方案二,采用compile=False

compile=False本质是忽略自定义损失函数错误,解释为:
if you wish to just perform inference with your model and not further optimization or training your model, you can simply wish to ignore the loss function

t=tf.keras.models.load_model(f'{model_path}', compile=False)

参考链接:

  1. https://stackoverflow.com/questions/57982158/valueerror-unknown-loss-functionfocal-loss-fixed-when-loading-model-with-my-cu

Edited by: Eshter
Date:2020120316

你可能感兴趣的:(tensorflow2.0,tensorflow)