Home > database >  In GAN network, I got error while trying to transform tensorflow dataset's to range [-1,1]
In GAN network, I got error while trying to transform tensorflow dataset's to range [-1,1]

Time:06-14

The images in the TensorFlow Fashion MNIST Dataset are in range of [0,255] and I wish to transform it to the range of tanh function [-1,1], for this I'm using the map function as shown below.

import tensorflow_datasets as tfds

def scale_images(data): 
    image = data['image']
    return (image - 127.5) / 127.5

ds = tfds.load('fashion_mnist', split='train')
ds = ds.map(scale_images) 

However it is giving me the error mentioned below.

File "<ipython-input-74-665c2cac0d84>", line 8, in scale_images  *
        return (image - 127.5) / 127.5

    TypeError: Expected uint8 passed to parameter 'y' of op 'Sub', got 127.5 of type 'float' instead. Error: Expected uint8, but got 127.5 of type 'float'.

It works perfectly when I use return image / 255 to reduce it to range [0,1] but it gives error when using the code shown above.

Please tell me how to transform the dataset's range to [-1,1].

EDIT:

For context I'm creating a GAN with this code as reference. However I have changed the activation of last layer of generator to tanh. Thus, I also need to change the images to the match the range of tanh output so that my discriminator is trained effectively. So I'm trying to modify the scale_images function to do the same.

CodePudding user response:

You can pass image / 255 but you can not pass (image - 127.5) / 127.5, So you can use below tricks:

Method_1 :

For going to the range [-1,1] from the range [0,1], you can use the simple trick (num*2)-1 like below:

def scale_images(data): 
    image = data['image']
    image = image / 255
    return (image * 2) - 1

Method_2:

You can use tf.cast(image, tf.float32) like below:

def scale_images(data): 
    image = data['image']
    image = tf.cast(image, tf.float32)
    return (image - 127.5) / 127.5
  • Related