Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

keras "unknown loss function" error after defining custom loss function

Tags:

keras

I defined a new loss function in keras in losses.py file. I close and relaunch anaconda prompt, but I got ValueError: ('Unknown loss function', ':binary_crossentropy_2'). I'm running keras using python2.7 and anaconda on windows 10.

I temporarily solve it by adding the loss function in the python file I compile my model.

like image 431
matchifang Avatar asked Aug 08 '17 19:08

matchifang


3 Answers

In Keras we have to pass the custom functions in the load_model function:

def my_custom_func():
    # your code
    return
from keras.models import load_model
model = load_model('my_model.h5', custom_objects={'my_custom_func':                   
my_custom_func})
like image 64
Pardhu Avatar answered Nov 13 '22 06:11

Pardhu


None of these solutions worked for me because I had two or more nested functions for multiple output variables.

my solution was to not compile when loading the model. I compile the model later on with the list of loss functions that were used when you trained the model.

from tensorflow.keras.models import load_model

# load model weights, but do not compile
model = load_model("mymodel.h5", compile=False)

# printing the model summary 
model.summary()

# custom loss defined for feature 1
def function_loss_o1(weights)
    N_c = len(weights)
    def loss(y_true, y_pred):
        output_loss = ... 
        return output_loss/N_c
    return loss

# custom loss defined for feature 2
def function_loss_o2(weights)
    N_c = len(weights)
    def loss(y_true, y_pred):
        output_loss = ... 
        return output_loss/N_c
    return loss 

# list of loss functions for each output feature
losses = [function_loss_o1, function_loss_o2]

# compile and train the model
model.compile(optimizer='adam', loss=losses, metrics=['accuracy'])

# now you can use compiled model to predict/evaluate, etc
eval_dict = {}
eval_dict["test_evaluate"] = model.evaluate(x_test, y_test, batch_size=batch_size, verbose=0)
like image 2
qubit10 Avatar answered Nov 13 '22 06:11

qubit10


I didn't have luck with the above solutions, but I was able to do this:

from keras.models import load_model
from keras.utils.generic_utils import get_custom_objects

get_custom_objects().update({'my_custom_func': my_custom_func})

model = load_model('my_model.h5')

I found the solution here: https://github.com/keras-team/keras/issues/5916#issuecomment-294373616

like image 1
Max Candocia Avatar answered Nov 13 '22 08:11

Max Candocia