Using custom layers in Functional API

I am trying to write a custom layer using subclassing in Keras and then use it in functional API. I followed the advise in the documentation - https://www.tensorflow.org/guide/keras/custom_layers_and_models#you_can_optionally_enable_serialization_on_your_layers but its not working for me. Here is my code snippet-

from tensorflow import keras
from tensorflow.keras import layers

class conv2D_Block(keras.layers.Layer):
    def __init__(self, filters, kernel_size=(3,3), strides=1, padding='same', pool_size=(2,2), 
**kwargs):
        super().__init__(**kwargs)
        
        self.filters = filters
        self.kernel_size = kernel_size 
        self.strides = strides 
        self.padding = padding 
        self.pool_size = pool_size 
        

        self.convlayer = layers.Conv2D(filters, kernel_size, strides = strides, padding= 
padding)  
        self.pool = layers.MaxPool2D(pool_size = pool_size)
        self.BatchNormalization = layers.BatchNormalization()

    def call(self, x):
        x = self.convlayer(x)
        x = keras.activations.relu(x)
        x = self.pool(x)
        x = self.BatchNormalization(x)
        return x

    def get_config(self):
        config = super(conv2D_Block, self).get_config()
        #config.update({filters:self.filters, kernel_size: self.kernel_size, 
        #strides:self.strides, padding:
        #              self.padding, pool_size: self.pool_size})
        config.update({convlayer: self.convlayer, pool: self.pool, BatchNormalization: 
        self.BatchNormalization})
        return config

layer1 = conv2D_Block(16)
config1 = layer1.get_config()

inputs = keras.Input(shape = (28,28,1))
inputs = conv2D_Block.from_config(config1)(inputs)
flatconv = layers.Flatten()(inputs)
output = layers.Dense(10,activation='softmax')(flatconv)
model = keras.Model(inputs = inputs, outputs = output)
model.compile(optimizer = 'adam', loss='sparsecategoricalcrossentropy', metrics = 'accuracy')

I understand that in the example given in the link, attributes of the model are simple (integer etc) while the example I am using has keras object attributes. I tried with minor changes to the code (using filter etc as attributes) but none of it works. For the above code, I am getting the error File C:\Users\Asus-ROG\Desktop\Machine learning\keras-convlayer.py, line 60, in inputs = conv2D_Block.from_config(config1)(inputs)

File C:\Users\Asus-ROG\anaconda3\envs\tf_gp\lib\site- 
packages\tensorflow\python\keras\engine\base_layer.py, line 697, in from_config
return cls(**config)

TypeError: __init__() missing 1 required positional argument: 'filters'

I have tried the obvious fixes(I hope) as you can see in the commented parts of the code. Can someone please help me out?

Topic keras

Category Data Science

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.