'Keras: Custom layer without inputs

I want to implement a Keras custom layer without any input, just trainable weights.

Here is the code so far:

class Simple(Layer):

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

    def build(self):
       self.kernel = self.add_weight(name='kernel', shape=self.output_dim, initializer='uniform', trainable=True)
       super(Simple, self).build()  

    def call(self):
       return self.kernel

    def compute_output_shape(self):
       return self.output_dim

X = Simple((1, 784))()

I am getting an error message:

__call__() missing 1 required positional argument: 'inputs'

Is there a workaround for building a custom layer without inputs in Keras?



Solution 1:[1]

Small correction: You need square brackets around self.output_dim:

def build(self, input_shapes):
   self.kernel = self.add_weight(name='kernel', shape=[self.output_dim], initializer='uniform', trainable=True)
   super(Simple, self).build(input_shapes)  

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 user18080866