Aviral Aggarwal
Aviral Aggarwal

Reputation: 23

I want to use keras layers within my custom layer, but I am unable to return the output of the layer as a tensor instead of an object

The error shown is Failed to convert object of type class 'tensorflow.python.keras.layers.pooling.MaxPooling2D' to Tensor. I have tried many things but I am unable to sort this error.

```class Mixed_pooling():
      def __init__(self, **kwargs):
          super(Mixed_pooling, self).__init__(**kwargs)

      def build(self, input_shape):
          self.alpha = self.add_weight(
          name='alpha', shape=(1,),
          initializer='random_normal',
          trainable=True
          )
          super(Mixed_pooling, self).build(input_shape)

      def call(self, x):
          x1 = tf.keras.layers.MaxPooling2D(pool_size=(2, 2), strides=(2,2), padding='VALID')
          x2 = tf.keras.layers.AveragePooling2D(pool_size=(2, 2), strides=(2,2), padding='VALID')
          outputs = tf.add(tf.multiply(x1, self.alpha), tf.multiply(x2, (1-self.alpha)))
          return outputs```

Upvotes: 1

Views: 476

Answers (1)

user11530462
user11530462

Reputation:

Providing the solution here (Answer Section) even though it is present in the Comment Section (Thanks to Slowpoke), for the benefit of the community.

As tf.keras.layers.MaxPooling2D() and tf.keras.layers.AveragePooling2D() are class objects, you need to instantiate the objects in build function and later use them in call function.

Modified Code -

import tensorflow as tf

class Mixed_pooling():
      def __init__(self, **kwargs):
          super(Mixed_pooling, self).__init__(**kwargs)

      def build(self, input_shape):
          self.alpha = self.add_weight(
          name='alpha', shape=(1,),
          initializer='random_normal',
          trainable=True
          )
          self.maxpool=tf.keras.layers.MaxPooling2D(pool_size=(2, 2), strides=(2,2), padding='VALID')
          self.avgpool =  tf.keras.layers.AveragePooling2D(pool_size=(2, 2), strides=(2,2), padding='VALID')
          super(Mixed_pooling, self).build(input_shape)

      def call(self, x):
          x1 = self.maxpool(x)
          x2 = self.avgpool(x)
          outputs = tf.add(tf.multiply(x1, self.alpha), tf.multiply(x2, (1-self.alpha)))
          return outputs

layer1 = Mixed_pooling()
print(layer1)

Output -

<__main__.Mixed_pooling object at 0x7fce31e46550>

Hope this answers your question. Happy Learning.

Upvotes: 0

Related Questions