Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
510 views
in Technique[技术] by (71.8m points)

python - Loading model with custom loss + keras

In Keras, if you need to have a custom loss with additional parameters, we can use it like mentioned on https://datascience.stackexchange.com/questions/25029/custom-loss-function-with-additional-parameter-in-keras

def penalized_loss(noise):
    def loss(y_true, y_pred):
        return K.mean(K.square(y_pred - y_true) - K.square(y_true - noise), axis=-1)
    return loss

The above method works when I am training the model. However, once the model is trained I am having difficulty in loading the model. When I try to use the custom_objects parameter in load_model like below

model = load_model(modelFile, custom_objects={'penalized_loss': penalized_loss} )

it complains ValueError: Unknown loss function:loss

Is there any way to pass in the loss function as one of the custom losses in custom_objects ? From what I can gather, the inner function is not in the namespace during load_model call. Is there any easier way to load the model or use a custom loss with additional parameters

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes, there is! custom_objects expects the exact function that you used as loss function (the inner one in your case):

model = load_model(modelFile, custom_objects={ 'loss': penalized_loss(noise) })

Unfortunately keras won't store in the model the value of noise, so you need to feed it to the load_model function manually.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...