Keras

Keras Customized Layer

Keras Customized Layer

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()

 

Top course recommendations for you

    Docker Swarm
    1 hrs
    Beginner
    1.7K+ Learners
    4.52  (107)
    Factorial Program in C
    2 hrs
    Beginner
    4.6K+ Learners
    4.43  (155)
    Jenkins Tutorial
    1 hrs
    Beginner
    8.5K+ Learners
    4.5  (599)
    Dockerize Spring Boot Application
    1 hrs
    Intermediate
    3.9K+ Learners
    4.42  (297)
    Python Data Structures
    1 hrs
    Beginner
    30.9K+ Learners
    4.51  (2315)
    Fibonacci Series in Java
    2 hrs
    Beginner
    2.7K+ Learners
    4.33  (60)
    Priority Queue in C++
    1 hrs
    Beginner
    2.2K+ Learners
    4.31  (98)
    Introduction to MATLAB
    2 hrs
    Beginner
    22.1K+ Learners
    4.41  (1676)
    Packages in Python
    1 hrs
    Beginner
    7.2K+ Learners
    4.32  (542)
    Palindrome in Python
    2 hrs
    Beginner
    2.9K+ Learners
    4.64  (86)