Reputation: 137
I'm currently building a GAN for images on my local directory. So I'm using the Keras.ImageDataGenerator flow_from_dir constructor.
I'd want to normalize my images between -1 and 1 that's the convention for GANs cause of the tanh activation.
I'm having problem in rescaling the image like implementing 1/127.5 -1 in the rescale argument.
from tensorflow.keras.preprocessing.image import ImageDataGenerator
fid = drive.ListFile({'q':"title='NM_cycleGAN.zip'"}).GetList()[0]['id']
f = drive.CreateFile({'id': fid})
f.GetContentFile('NM_cycleGAN.zip')
PATH = '/content/NM_CycleGAN'
train_A_dir = os.path.join(PATH, 'Train_A')
train_A = os.path.join(train_A_dir, 'Negroid')
trainA_image_generator = ImageDataGenerator(rescale=1./127.5 - 1)
train_A = trainA_image_generator.flow_from_directory(batch_size=batch_size,
directory=train_A_dir,
shuffle=True, seed=1,
target_size=(128, 128),
class_mode=None)
inpA = next(iter(train_A))
print(inpA[0].min())
-253
Upvotes: 0
Views: 2054
Reputation: 11218
First of rescale
parameter multiplies the data with a scalar, usually we use 1/255.
This makes the mean of the data at 0.5 with range 0. to 1.
After that, we can use featurewise_center and samplewise_center to make sure our mean is at 0., which will ensure the data has range -0.5 to 0.5
Now, with these in mind, you can choose your proper scaling factor.
tf.keras.preprocessing.image.ImageDataGenerator(
featurewise_center=True, samplewise_center=True,
rescale = 2/255.
)
With these parameter you'll get the desired behaviour. A small snippet running the datagen:
x = np.random.randint(0,255, (10,224,224,3))
datagen = tf.keras.preprocessing.image.ImageDataGenerator(
featurewise_center=True, samplewise_center=True,
rescale = 2/255.
)
for x_i in datagen.flow(x, batch_size = 5):
print(np.mean(x_i))
print(np.min(x_i))
print(np.max(x_i))
break
Out:
-1.0709576e-08
-0.9992176
0.9986379
As you can see the mean is 0
, the min is -1
and max is +1
.
ref: https://www.tensorflow.org/api_docs/python/tf/keras/preprocessing/image/ImageDataGenerator
Upvotes: 4