简体   繁体   English

保存/加载 Tensorflow Keras model 仅用于预测

[英]Save / Load Tensorflow Keras model for Prediction only

I have a tensorflow keras model with custom losses.我有一个自定义损失的 tensorflow keras model。 After trianing, I want to store the model using model.save(path) and in another python script load the model for prediction only using model = tf.keras.models.load_model(model_path, compile=False) . After trianing, I want to store the model using model.save(path) and in another python script load the model for prediction only using model = tf.keras.models.load_model(model_path, compile=False) .

Without compile=False , tensorflow will complain about the missing loss function.如果没有compile=False ,tensorflow 将抱怨丢失的损失 function。 Calling model.prediction however will result in a Model object has no attribute 'loss' error message.然而,调用model.prediction将导致Model object has no attribute 'loss'错误消息。 I would like to call model.predict without needing to specify the loss again.我想调用model.predict而无需再次指定损失。

Is there a solution to save/load a tf.keras.Model without the custom loss to using the model for prediction?是否有一种解决方案可以保存/加载tf.keras.Model而不会因使用 model 进行预测而造成自定义损失?

Code代码

Since it was asked, the model trains on multiple outputs / losses and I define the losses with lambdas to capture weightings etc. This looks like this:既然被问到,model 训练多个输出/损失,我用 lambdas 定义损失以捕获权重等。这看起来像这样:

losses = [lambda y_true, y_pred: util.weighted_mse_loss(y_true, y_pred, tf.square(gain_weight)), 
        lambda y_true, y_pred: util.weighted_mse_loss(y_true, y_pred, tf.square(Rd_weight)), 
        lambda y_true, y_pred: util.pole_zero_loss(y_true, y_pred, r_weight, w_weight),
        lambda y_true, y_pred: util.pole_zero_loss(y_true, y_pred, r_weight, w_weight)]


model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=10E-4),
    loss=losses)

As mentioned here keras has tf.keras.models.load_model(filepath, custom_objects=None, compile=True) function.正如这里提到的 keras 有tf.keras.models.load_model(filepath, custom_objects=None, compile=True) function。 If you have custom loss, you can use:如果您有自定义损失,您可以使用:

model = keras.models.load_model('model.h5', custom_objects={'my_loss': my_loss})

Where 'my_loss' is your loss' name, and my_loss is the function.其中“my_loss”是您的损失名称,my_loss 是 function。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM