Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading model with custom loss function: ValueError: 'Unknown loss function' in keras

Tags:

keras

Compiling the model then saving. Then while loading model that time getting error.

def triplet_loss(y_true, y_pred, alpha = 0.3):
    anchor, positive, negative = y_pred[0], y_pred[1], y_pred[2]
    pos_dist = tf.reduce_sum(tf.square(tf.subtract(anchor, positive)), axis=-1)
    neg_dist = tf.reduce_sum(tf.square(tf.subtract(anchor, negative)), axis=-1)
    basic_loss = tf.add(tf.subtract(pos_dist, neg_dist), alpha)
    loss = tf.reduce_sum(tf.maximum(basic_loss, 0.0))

    return loss

FRmodel.compile(optimizer = 'adam', loss = triplet_loss, metrics = 
['accuracy'])
FRmodel.save('model.h5')




`FRmodel = load_model('model.h5')`

ValueError: Unknown loss function:triplet_loss
like image 475
Nishant Avatar asked Jun 11 '26 05:06

Nishant


1 Answers

Use custom_objects when loading your model:

def def triplet_loss(y_true, y_pred, alpha = 0.3):
    anchor, positive, negative = y_pred[0], y_pred[1], y_pred[2]
    pos_dist = tf.reduce_sum(tf.square(tf.subtract(anchor, positive)), axis=-1)
    neg_dist = tf.reduce_sum(tf.square(tf.subtract(anchor, negative)), axis=-1)
    basic_loss = tf.add(tf.subtract(pos_dist, neg_dist), alpha)
    loss = tf.reduce_sum(tf.maximum(basic_loss, 0.0))

    return loss

FRmodel = load_model('model.h5',custom_objects={'triplet_loss':triplet_loss})

Are you loading the siamese or the base_model?

like image 167
Javier Naranjo Alcázar Avatar answered Jun 27 '26 23:06

Javier Naranjo Alcázar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!