Search code examples
pythontensorflowkerasautoencodermnist

MNIST Autoencoder: ValueError: total size of new array must be unchanged, input_shape = [748], output_shape = [28, 28]


I'm trying to build a mnist autoencoder to learn how to work with reshaping and encoding.

The following error is thrown when i run the code:

ValueError: total size of new array must be unchanged, input_shape = [748], output_shape = [28, 28]

The code looks like this:

import tensorflow as tf
import tensorflow.keras as keras
from tensorflow.keras import layers

mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255., x_test / 255.

enc_in = tf.keras.Input(shape=(28, 28))
x = layers.Flatten()(enc_in)
x = layers.Dense(128, activation='relu', name='enc_dense_1')(x)
enc_out = layers.Dense(10, activation='softmax', name='enc_out')(x)
x = layers.Dense(128, activation='relu', name='dec_dense_1')(enc_out)
x = layers.Dense(748, activation='relu', name='dec_dense_2')(x)
dec_out = layers.Reshape(target_shape=(28, 28))(x)

autoencoder = keras.Model(inputs=enc_in, outputs=dec_out)
autoencoder.compile(
    optimizer='adam',
    loss=keras.losses.CategoricalCrossentropy(),
    metrics=['accuracy']
)

print(autoencoder.summary())

autoencoder.fit(x_train, x_train, batch_size=64, epochs=10, validation_split=0.2)

Why is tensorflow complaining about the output shape while my keras.Input shape is (28, 28) ?


Solution

  • The error is quite self-explanatory, you made a small mistake.

    #28 * 28 = 784
    
    x = layers.Dense(748, activation='relu', name='dec_dense_2')(x)
    dec_out = layers.Reshape(target_shape=(28, 28))(x)
    

    You accidentally wrote 748 instead of 784, and of course the reshape cannot take place due to this error.