How to set possbility to tf.keras.layers.RandomFlip?


Is there possible to set a possibility when doing random flip operations by using tf.keras.layers.RandomFlip ?

for example:

def augmentation():
        data_augmentation = keras.Sequential([
            keras.layers.RandomFlip("horizontal", p=0.5),
            keras.layers.RandomRotation(0.2, p=0.5)
   return data_augmentation 


Try creating a simple Lambda layer and defining your probability in a separate function:

import random

def random_flip_on_probability(image, probability= 0.5):
    if random.random() < probability:
      return tf.image.random_flip_left_right(image)
    return image

def augmentation():
        data_augmentation = keras.Sequential([
            keras.layers.RandomRotation(0.2, p=0.5)
   return data_augmentation 

If you need to use data augmentation during training or inference, you will have to define your own custom layer. Try something like this:

class RandomFlipOnProbability(tf.keras.layers.Layer):
  def __init__(self, probability):
    super(MyDenseLayer, self).__init__()
    self.probability = probability

  def call(self, images):
    if random.random() < self.probability:
      return tf.image.flip_left_right(images)
    return images

Answered By – AloneTogether

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published