Hi i'm working on the deployment of a trained capsule network model into web application and i have a problem loading the model in other .py file to make predictions. i tried get.config() and custom_objects{} method and that solved only the custom layers/classes problem but i have several custom functions (squash, margin_loss,..etc):

class Length(layers.Layer):
    def call(self, inputs, **kwargs):
        return K.sqrt(K.sum(K.square(inputs), -1))

    def compute_output_shape(self, input_shape):
        return input_shape[:-1]
    def get_config(self):
        config = super(Length, self).get_config()
        return config

class Mask(layers.Layer):

    def call(self, inputs, **kwargs):
        # use true label to select target capsule, shape=[batch_size, num_capsule]
        if type(inputs) is list:  # true label is provided with shape = [batch_size, n_classes], i.e. one-hot code.
            assert len(inputs) == 2
            inputs, mask = inputs
        else:  # if no true label, mask by the max length of vectors of capsules
            x = inputs
            # Enlarge the range of values in x to make max(new_x)=1 and others < 0
            x = (x - K.max(x, 1, True)) / K.epsilon() + 1
            mask = K.clip(x, 0, 1)  # the max value in x clipped to 1 and other to 0

        # masked inputs, shape = [batch_size, dim_vector]
        inputs_masked = K.batch_dot(inputs, mask, [1, 1])
        return inputs_masked

    def compute_output_shape(self, input_shape):
        if type(input_shape[0]) is tuple:  # true label provided
            return tuple([None, input_shape[0][-1]])
            return tuple([None, input_shape[-1]])
    def get_config(self):
        config = super(Mask, self).get_config()
        return config

def squash(vectors, axis=-1):
    s_squared_norm = tf.reduce_sum(tf.square(vectors), axis, keep_dims=True)
    scale = s_squared_norm / (1 + s_squared_norm) / tf.sqrt(s_squared_norm + K.epsilon())
    return tf.multiply(scale, vectors)

I've tried both load_model() and model_from_json():

model1 = load_model('model2.h5', custom_objects={'ClassCapsule':ClassCapsule, 'Length':Length, 'Mask':Mask, 'tf': tf, 'squash': squash })

model = model_from_json(loaded_model_json, custom_objects={'ClassCapsule':ClassCapsule, 'Length':Length, 'Mask':Mask, 'tf': tf, 'squash': squash})

i keep getting this error:

NameError: name 'squash' is not defined

Can you please help me fix this , or if there is another way to save/load non sequential models with custom classes/functions.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.