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.4K+ Learners
    4.57  (72)
    Factorial Program in C
    2 hrs
    Beginner
    3.9K+ Learners
    4.43  (129)
    Jenkins Tutorial
    1 hrs
    Beginner
    7K+ Learners
    4.54  (369)
    Dockerize Spring Boot Application
    1 hrs
    Intermediate
    2.9K+ Learners
    4.37  (111)
    Python Data Structures
    1 hrs
    Beginner
    23.9K+ Learners
    4.54  (1275)
    Fibonacci Series in Java
    2 hrs
    Beginner
    2.4K+ Learners
    4.38  (48)
    Priority Queue in C++
    1 hrs
    Beginner
    1.9K+ Learners
    4.32  (84)
    Introduction to MATLAB
    2 hrs
    Beginner
    18.1K+ Learners
    4.51  (1034)
    Packages in Python
    1 hrs
    Beginner
    5.8K+ Learners
    4.41  (221)
    Palindrome in Python
    2 hrs
    Beginner
    2.4K+ Learners
    4.69  (62)