pythontensorflowautoencoderencoder

Tensorflow autoencoder attempt: ValueError: Output tensors of a Functional model must be the output of a TensorFlow `Layer`


I am encountering the following error while trying to write an encoder model for a variational autoencoder:

ValueError: Output tensors of a Functional model must be the output of a TensorFlow `Layer` (thus holding past layer metadata). Found: [[-0.02135764 -0.01809833  0.00880998 ... -0.02307652  0.00028993 0.00441882]...

Below is a simplified version of my code. The issue appears to be coming from the type of x, which is apparently <class 'tensorflow.python.framework.ops.EagerTensor'>.

def encoder(inputs, latent_dim):

encoder_inputs = tf.keras.Input(shape=(None, 248, 40, 1), name="input_layer")
x = tf.keras.layers.ZeroPadding2D(padding=(3, 0))(inputs)
x = tf.keras.layers.Conv2D(32, (9, 1), strides=(5, 1), batch_size=batch_size)(x)

model = tf.keras.Model(encoder_inputs, x, name="encoder")
return model

I have tried creating the model with output x.output instead of simply x, but EagerTensors have no such attribute. :( What am I doing wrong? Thanks in advance.

Some additional code to provide more context. I'm calling the function as follows, where X_train is a 20x248x40x1 numpy array (20 inputs of shape 248x40x1).

model1 = encoder(X_train, 100)

Solution

  • It should be

    encoder_inputs

    on the first line like here:

    encoder_inputs = keras.Input(shape=(None, None, 3))
    processed = keras.layers.RandomCrop(width=32, height=32)(encoder_inputs)
    conv = keras.layers.Conv2D(filters=2, kernel_size=3)(processed)
    pooling = keras.layers.GlobalAveragePooling2D()(conv)
    feature = keras.layers.Dense(10)(pooling)
    
    full_model = keras.Model(encoder_inputs, feature)
    backbone = keras.Model(processed, conv)
    activations = keras.Model(conv, feature)
    

    Or more specific it is about what you are trying to do ... you want an model that does the computation so create the model than add stuff to it. So i define your encoder and its layer structure

    def encoder():
    
      encoder_inputs = tf.keras.Input(shape=(None, 248, 40, 1), 
                                      name="input_layer")
      x = tf.keras.layers.ZeroPadding2D(padding=(3, 0))(encoder_inputs)
      x = tf.keras.layers.Conv2D(32, (9, 1), strides=(5, 1), 
      batch_size=batch_size)(x)
    
      model = tf.keras.Model(encoder_inputs, x, name="encoder")
      return model
    

    then inputs is used later like here, for example to minimize the Mean square error between your inputs and some targets with the encoder model:

      inputs = your_inputs
      targets = yout targets
      model = encoder()
      model.compile(optimizer="Adam", loss="mse", metrics=["mae", "acc"])
      model.fit(inputs,targets)
    

    More info can be found at tf.keras.Model