Keras custom layer

I'm using Keras and want to create custom layer with its trained weights. What is the proper way to do that?

keraskeras-layer
3 votesNN138.00
1 Answers
JW234.00
2

In order to create a keras custom layer, you need to create a class and extend from Layer class.

Take a look how you can write it.

from keras import backend as K
from keras.layers import Layer

class MyLayer(Layer):

    def __init__(self, output_dim, **kwargs):
        self.output_dim = output_dim
        super(MyLayer, self).__init__(**kwargs)

    def build(self, input_shape):
        # Create a trainable weight variable for this layer.
        self.kernel = self.add_weight(name='kernel', 
                                      shape=(input_shape[1], self.output_dim),
                                      initializer='uniform',
                                      trainable=True)
        super(MyLayer, self).build(input_shape)  # Be sure to call this at the end

    def call(self, x):
        return K.dot(x, self.kernel)

    def compute_output_shape(self, input_shape):
        return (input_shape[0], self.output_dim)

All these 3 methods need to be overrided.
Also here is the doc of Keras https://keras.io/layers/writing-your-own-keras-layers/

Reply
Couldn't find what you were looking for?and we will find an expert to answer.
How helpful was this page?