In Keras, you can also create a customized layer with the help of its base layer. In this chapter, we will create a customized layer in Keras with the following steps:
Step – 1: Import required modules
- The necessary modules can be imported with the following code:
- from keras import backend as ker
- from keras.layers import Layer
Step – 2: Create and initialize a layer class
To create and initialize a layer class, follow the code snippet below:
class LayerCustom (Layer):
The class can be initiated with the following code:
def __init__ (self, dim, **args):
self.dim = dim
super (LayerCustom, self).__init__(**args)
Step – 3: Define the build method
The build method can be implemented by using the code below:
self.kernel = self.add_weight(name = ‘build_method’,
shape = (input_shape[3], self.dim),
initializer = ‘normal’, trainable = True)
super(LayerCustom, self).build(inp_shp)
Step – 4: Define the call method
The call method is used to implement the exact working of the layer while training the model.
The custom call that we created is as follows:
def call(self, inp_data):
return K.dot(inp_data, self.kernel)
Step – 5: Define the compute_output_shape method
The method can be implemented as follows:
def compute_output_shape (self, inp_shp): return (inp_shp[0], self.dim)
After implementing all these steps, we are going to create a simple model with the help of our customized layer below:
from keras.models import Sequential
from keras.layers import Dense
model = Sequential()
model.add(LayerCustom(32, input_shape = (22,)))
model.add(Dense(8, activation = 'softplus')) model.summary()