[英]keras won't recognize custom objects
I am loading my model using custom a custom loss function but when I run the code I get an error: ValueError: Unknown loss function:dice_coef_loss
.我正在使用自定义的自定义损失函数加载我的模型,但是当我运行代码时出现错误:
ValueError: Unknown loss function:dice_coef_loss
。 The was created using 2 GPUs.这是使用 2 个 GPU 创建的。 When I save the model using 1 GPU the
load_model()
I don't get the error.当我使用 1 GPU 保存模型时,
load_model()
我没有收到错误消息。 Is there a reason why a multi-gpu trained model would not recognize custom_objects
?多 GPU 训练模型无法识别
custom_objects
是否有原因?
import tensorflow as tf
from tensorflow.keras.models import load_model
from tensorflow.keras import backend as K
def dice_coef(y_true, y_pred):
y_true_f = K.flatten(y_true)
y_pred_f = K.flatten(y_pred)
intersection = K.sum(y_true_f * y_pred_f)
return (2. * intersection + smooth) / (K.sum(y_true_f) + K.sum(y_pred_f) + smooth)
def dice_coef_loss(y_true, y_pred):
return -dice_coef(y_true, y_pred)
load_model('test_2gpus_model', custom_objects = {'dice_coef': dice_coef, 'dice_coef_loss': dice_coef_loss}))
I have also tried:我也试过:
load_model('test_2gpus_model', custom_objects = {'dice_coef': dice_coef(y_true, y_pred), 'dice_coef_loss': dice_coef_loss(y_true, y_pred)}))
but then I get the error NameError: name 'y_true' is not defined
但后来我收到错误
NameError: name 'y_true' is not defined
I had the same problem because the function definition was in another class other than the one I am calling the load_model from.我遇到了同样的问题,因为函数定义在另一个类中,而不是我从中调用 load_model 的类。 when I copied the function definitions inside the class that calls the load_model, it worked.
当我在调用 load_model 的类中复制函数定义时,它起作用了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.