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.8K+ Learners
    4.5  (126)
    Factorial Program in C
    2 hrs
    Beginner
    5.3K+ Learners
    4.46  (556)
    Jenkins Tutorial
    1 hrs
    Beginner
    8.7K+ Learners
    4.53  (710)
    Dockerize Spring Boot Application
    1 hrs
    Intermediate
    4.1K+ Learners
    4.46  (325)
    Python Data Structures
    1 hrs
    Beginner
    31.8K+ Learners
    4.5  (2546)
    Fibonacci Series in Java
    2 hrs
    Beginner
    2.8K+ Learners
    4.39  (69)
    Priority Queue in C++
    1 hrs
    Beginner
    2.2K+ Learners
    4.38  (110)
    Introduction to MATLAB
    2 hrs
    Beginner
    22.5K+ Learners
    4.41  (1798)
    Packages in Python
    1 hrs
    Beginner
    7.4K+ Learners
    4.33  (568)
    Palindrome in Python
    2 hrs
    Beginner
    2.9K+ Learners
    4.65  (92)