ValueError when saving Autoencoder TF example

Following the example at:

I try to save the following autoencoder:

latent_dim = 64 

class Autoencoder(Model):
  def __init__(self, latent_dim):
    super(Autoencoder, self).__init__()
    self.latent_dim = latent_dim   
    self.encoder = tf.keras.Sequential([
      layers.Dense(latent_dim, activation='relu'),
    self.decoder = tf.keras.Sequential([
      layers.Dense(784, activation='sigmoid'),
      layers.Reshape((28, 28))

  def call(self, x):
    encoded = self.encoder(x)
    decoded = self.decoder(encoded)
    return decoded

autoencoder = Autoencoder(latent_dim)

But when I try te solve the autoencoder model, I get ValueError:"Some-name")

WARNING:tensorflow:Skipping full serialization of Keras layer <__main__.Autoencoder object at 0x78fbbf0cb940>, because it is not built.
ValueError                                Traceback (most recent call last)
<ipython-input-4-718fe2c89223> in <cell line: 1>()
----> 1"delete_this")

1 frames
/usr/local/lib/python3.10/dist-packages/keras/saving/legacy/ in raise_model_input_error(model)
     95     # If the model is not a `Sequential`, it is intended to be a subclassed
     96     # model.
---> 97     raise ValueError(
     98         f"Model {model} cannot be saved either because the input shape is not "
     99         "available or because the forward pass of the model is not defined."

ValueError: Model <__main__.Autoencoder object at 0x78fbbf0cb940> cannot be saved either because the input shape is not available or because the forward pass of the model is not defined.To define a forward pass, please override ``. To specify an input shape, either call `build(input_shape)` directly, or call the model on actual data using `Model()`, ``, or `Model.predict()`. If you have a custom training step, please make sure to invoke the forward pass in train step through `Model.__call__`, i.e. `model(inputs)`, as opposed to ``.

How can I solve this?
How can I save a custom Keras model?

I already tried to provide, 28, 28, 1)) but same error.

Thank you!


To save a model this way in TF you need to run a forward pass. This is because TensorFlow needs to know the whole computational graph for the model to frozen.

In your case, you instantiated the model, but you did not cover the call. You could simply do:

autoencoder(tf.constant([1])) # or anything else that fits your desired data shape

and then"Some-name")

should work.

The error you see is trying to hint at this.