[Python] How to match the output shape of generator and the input shape of discriminator in...

Discussão em 'Python' iniciado por Stack, Agosto 9, 2025.

  1. Stack

    Stack Membro Participativo

    I am working on my first GANs model, I've followed Tensorflow's official documentation using MNIST dataset. I've run it smoothly. I tried to replace MNIST with my own dataset, I've prepared it to match the same size as MNIST: 28 * 28, it works.

    However, my dataset is more complicated than MNIST so I tried to make the image size of my dataset larger: 512 * 512, but I keep getting errors related to input & output shape. I couldn't figure out the relationship between all these input and output shapes of the discriminator and generator. Assuming I want to change my dataset from 28 * 28 (MNIST size) to y*y (custom size) which input/output shapes exactly I need to tune in these layers? and why? anyone could clarify this flow?

    This is my code where I reshape my datasets to match MNIST size:

    train_images = train_images.reshape(train_images.shape[0], 28, 28, 1).astype('float32')


    and here I normalize it :

    train_images = (train_images - 127.5) / 127.5 # Normalize the images to [-1, 1]


    This is the generator model where the output shape of the last layer indicating something 28 * 28:

    def make_generator_model():
    model = tf.keras.Sequential()
    model.add(layers.Dense(7*7*256, use_bias=False, input_shape=(100,)))
    model.add(layers.BatchNormalization())
    model.add(layers.LeakyReLU())

    model.add(layers.Reshape((7, 7, 256)))
    assert model.output_shape == (None, 7, 7, 256) # Note: None is the batch size

    model.add(layers.Conv2DTranspose(128, (5, 5), strides=(1, 1), padding='same', use_bias=False))
    assert model.output_shape == (None, 7, 7, 128)
    model.add(layers.BatchNormalization())
    model.add(layers.LeakyReLU())

    model.add(layers.Conv2DTranspose(64, (5, 5), strides=(2, 2), padding='same', use_bias=False))
    assert model.output_shape == (None, 14, 14, 64)
    model.add(layers.BatchNormalization())
    model.add(layers.LeakyReLU())

    model.add(layers.Conv2DTranspose(1, (5, 5), strides=(2, 2), padding='same', use_bias=False, activation='tanh'))
    assert model.output_shape == (None, 28, 28, 1)

    return model


    This is the discriminator model, where the input of the first layer indicating something 28 * 28:

    def make_discriminator_model():
    model = tf.keras.Sequential()
    model.add(layers.Conv2D(64, (5, 5), strides=(2, 2), padding='same',
    input_shape=[28, 28, 1]))
    model.add(layers.LeakyReLU())
    model.add(layers.Dropout(0.3))

    model.add(layers.Conv2D(128, (5, 5), strides=(2, 2), padding='same'))
    model.add(layers.LeakyReLU())
    model.add(layers.Dropout(0.3))

    model.add(layers.Flatten())
    model.add(layers.Dense(1))

    return model

    Continue reading...

Compartilhe esta Página