What is the correct way of loading a keras model with custom objects?

42 views Asked by At

I am trying to load a keras model with a custom loss, accuracy, and distance functio using tensorflow.keras.load_model() and passing custom_objects as an arg. On all of my attempts, I get a fatal error and my kernel is restarted: Windows fatal exception: access violation.

I am aware of a number of posts relating to this issue - but these solutions don't seem to fix my problem: Keras load_model with custom objects doesn't work properly Loading model with custom loss + keras How do I load a keras saved model with custom Optimizer

Here are the custom functions used by my saved model:

def EuclDistance(vects):
    x, y = vects
    sum_square = K.sum(K.square(x - y), axis=1, keepdims=True)
    return K.sqrt(K.maximum(sum_square, K.epsilon()))
    
def EuclDistanceShape(shapes):
    shape1, shape2 = shapes
    return (shape1[0], 1)
    

def accuracy(y_true, y_pred):

    # Check if predicted values are less than 0.5
    thresholded_preds = y_pred < 0.5
    
    # Cast boolean results to the same type as y_true
    thresholded_preds = K.cast(thresholded_preds, y_true.dtype)
    
    # Compare true labels with the casted predicted values
    correct_predictions = K.equal(y_true, thresholded_preds)
    
    # Mean of boolean tensor
    accuracy = K.mean(correct_predictions)

    return accuracy

def ContrastiveLoss(y_true, y_pred, margin = 1):
    
    y_true = tf.cast(y_true, tf.float32)

    sqaure_pred = K.square(y_pred)
    margin_square = K.square(K.maximum(margin - y_pred, 0))
    return K.mean(y_true * sqaure_pred + (1 - y_true) * margin_square)

Here is how I have tried to load my model:

# Define path to our model 
model_path = 'Siamese.h5'

# If it exists, load existing model - else train model
if os.path.exists(model_path):
    model = load_model(model_path,
                       custom_objects = {'EuclDistance': EuclDistance,
                                         'EuclDistanceShape': EuclDistanceShape,
                                         'ContrastiveLoss': ContrastiveLoss,
                                         'accuracy': accuracy})
else:
    model = train_model()

I only need to load my model to make predictions. I saw another possible solution might be to load the model without compiling in the case where it will only be used to make predictions: https://stackoverflow.com/a/67010429/14627147. This did not work either.

0

There are 0 answers