PascalIv
PascalIv

Reputation: 615

Python Keras: Unable to load model with a custom layer although it has get_config

I used a custom layer for my Keras model, namely the DepthwiseConv3D layer. I trained the model and saved it using model.save("model.h5")

from DepthwiseConv3D import DepthwiseConv3D

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

But I am getting "TypeError: unorderable types: NoneType() > int()", raised by DepthWiseConv3D at:

if (self.groups > self.input_dim):
       raise ValueError('The number of groups cannot exceed the number of channels')

The layers config is:

 def get_config(self):
        config = super(DepthwiseConv3D, self).get_config()
        config.pop('filters')
        config.pop('kernel_initializer')
        config.pop('kernel_regularizer')
        config.pop('kernel_constraint')
        config['depth_multiplier'] = self.depth_multiplier
        config['depthwise_initializer'] = initializers.serialize(self.depthwise_initializer)
        config['depthwise_regularizer'] = regularizers.serialize(self.depthwise_regularizer)
        config['depthwise_constraint'] = constraints.serialize(self.depthwise_constraint)
        return config

I instantiated my layer as

x = DepthwiseConv3D(kernel_size=(7,7,7),
                depth_multiplier=1,groups=9, 
                padding ="same", use_bias=False,
                input_shape=(50, 37, 25, 9))(x)
x = DepthwiseConv3D(depth_multiplier= 32, groups=8, kernel_size=(7,7,7), 
                strides=(2,2,2), activation='relu', padding = "same")(x)
x = DepthwiseConv3D(depth_multiplier= 64, groups=8, kernel_size=(7,7,7), 
                strides=(2,2,2), activation='relu', padding = "same")(x)

How can I load my model?

Upvotes: 0

Views: 326

Answers (1)

Dr. Snoopy
Dr. Snoopy

Reputation: 56357

The get_config method in the custom layer you are using is not correctly implemented, it does not save all the parameters that it needs, so it errors when loading back the model.

If you can instance the model using the same original code, you can load the weights from the same file using model.load_weights. This is just a workaround to the problem, and it should work. A proper solution would be to implement a correct version of get_config, and that would require re-training the model.

Upvotes: 1

Related Questions