Search code examples
tensorflowkeraskeras-layer

Writing your own layer


I am very new to keras. I'm trying to write (using Functional API) a custom layer in Keras as in Keras.io

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(shape=(input_shape[1], self.output_dim),
                                      initializer='uniform',
                                      trainable=True)
        super(MyLayer, self).build(input_shape)  # Be sure to call this somewhere!

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

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

calling as :

sourcedistribution = Mylayer(dropout2_target)

The error traceback is as follows:

File "/root/PycharmProjects/chNET/modelBuild.py", line 77, in 
model = create_network([100, 100, 3])
File "/root/PycharmProjects/chNET/modelBuild.py", line 53, in create_network
sourcedistribution = Mylayer(dropout2_source)
NameError: global name 'Mylayer' is not defined

Please help to understand this error.


Solution

  • I think the only issue is you have defined MyLayer but you are calling it Mylayer.