Home > database >  Keras:'TypeError: Failed to convert object of type <class 'tuple'> to Tensor�
Keras:'TypeError: Failed to convert object of type <class 'tuple'> to Tensor�

Time:10-29

I defined a layer base on a class.The purpose of this layer is only to add a learnable weight to the input. The input and output sizes passing through this layer are the same. When I build the model,the error occured:

TypeError: Failed to convert object of type <class 'tuple'> to Tensor. Contents: (None, 256, 256). Consider casting elements to a supported type.

Here is the code(defined and called).

Defined:

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

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

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

def compute_output_shape(self, input_shape):
    return input_shape

Called:

 fre_dct = Input(shape=(256, 256))
 fw_low = Filter_low(name='Filter_low')(fre_dct)

CodePudding user response:

Try changing the input_shape in your kernel like this:

import tensorflow as tf

class Filter_low(tf.keras.layers.Layer):

  def __init__(self,**kwargs):
      
      super(Filter_low, self).__init__(**kwargs)

  def build(self, input_shape):
      output_dim = input_shape[-1]
      self.kernel = self.add_weight(name='kernel',
                                    shape=(output_dim, output_dim),
                                    initializer='uniform',
                                    trainable=True)
      super(Filter_low, self).build(input_shape)  

  def call(self, x):
      return tf.keras.backend.dot(x, self.kernel)

  def compute_output_shape(self, input_shape):
      return input_shape

fre_dct = tf.keras.Input(shape=(256, 256))
fw_low = Filter_low(name='Filter_low')(fre_dct)
model = tf.keras.Model(fre_dct, fw_low)

X = tf.random.normal((5, 256, 256))
y = tf.random.normal((5, 256, 256))
model.compile(optimizer='adam', loss='MSE')
model.fit(X, y, epochs=2)

Alternatively, you can set shape=(input_shape[1:]).

  • Related