3

I'm creating an autoencoder in Keras following this tutorial and I keep getting the following error.

decoder = tf.keras.Model(encoded_input, decoded(input_img))
TypeError: 'Tensor' object is not callable

I believe it's something to do with not being able to use tensors in this way because of the nature of this type of object but I have some gaps in understanding of why and how to go about solving this.

Here is a minimal working example of my code:

# input_img input placeholder
input_img = tf.keras.layers.Input(shape=(16, 16, 1), name ="input")
encoded = tf.keras.layers.Dense(encoding_dim, activation='relu')(input_img)
decoded = tf.keras.layers.Dense(256, activation='sigmoid')(encoded)
autoencoder = tf.keras.Model(input_img, decoded)
encoder = tf.keras.Model(input_img, encoded)
encoded_input = tf.keras.layers.Input(shape=(encoding_dim,))
decoder = tf.keras.Model(input_img, decoded(encoded_input))

1 Answer 1

1

Keras Model expects input & output arguments as layers, not tensors. The tutorial is correct - you appear to have missed a line right before decoder =: -- decoder_layer = autoencoder.layers[-1]

All together, with decoder = changed appropriately:

input_img = tf.keras.layers.Input(shape=(16, 16, 256), name ="input")
encoded   = tf.keras.layers.Dense(encoding_dim, activation='relu')(input_img)
decoded   = tf.keras.layers.Dense(256, activation='sigmoid')(encoded)

autoencoder = tf.keras.Model(input_img, decoded)
encoder     = tf.keras.Model(input_img, encoded)

encoded_input = tf.keras.layers.Input(shape=(encoding_dim,))
decoder_layer = autoencoder.layers[-1] # gets 'decoded' = last layer of 'autoencoder'

decoder = tf.keras.Model(encoded_input, decoder_layer(encoded_input))
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the explanation. I'm getting this error now, ValueError: A target array with shape (1000, 16, 16, 1) was passed for an output of shape (None, 16, 16, 256) while using as loss binary_crossentropy This loss expects targets to have the same shape as the output. I assume I need to reshape my tensors at some point or change the model architecture so the input and output are identical.
Autoencoders seek to reconstruct their input - thus, output & input dims must match. Dense(256) w/ 'sigmoid' yields 256 output predictions - whereas your Input has 1 input label, i.e. last dim in shape=. Fix: Input(shape=(16,16,256)).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.