且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用自定义损失函数加载Keras模型?

更新时间:2023-12-01 21:14:10

由于您在模型中使用了 custom 损失函数,因此当将模型持久保存在磁盘上时,将不会保存损失函数,并且而是仅将其名称包含在模型文件中.然后,当您想在以后重新加载模型时,需要将存储名称对应的损失函数告知模型.要提供该映射,可以使用load_model_hdf5函数的custom_objects自变量:

Since you are using a custom loss function in your model, the loss function would not be saved when persisting the model on disk and instead only its name would be included in the model file. Then, when you want to load back the model at a later time, you need to inform the model of the corresponding loss function for the stored name. To provide that mapping, you can use custom_objects argument of load_model_hdf5 function:

load_model_hdf5(filepath = "modelpath", custom_objects = list(RMSE = RMSE))

或者,在训练结束后,如果您只想使用模型进行预测,则可以将compile = FALSE参数传递给load_model_hdf5函数(因此,将不需要并加载损失函数):

Alternatively, after training is finished, if you just want to use the model for prediction you can just pass compile = FALSE argument to load_model_hdf5 function (hence, the loss function would not be needed and loaded):

load_model_hdf5(filepath = "modelpath", compile = FALSE)