How to use data augmentation in TensorFlow?

by noemy.bosco , in category: General Help , a year ago

How to use data augmentation in TensorFlow?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by adelia , a year ago

@noemy.bosco 

To use data augmentation in TensorFlow, you can follow these steps:

  1. Import the necessary libraries:
1
2
import tensorflow as tf
from tensorflow.keras.preprocessing.image import ImageDataGenerator


  1. Create an instance of the ImageDataGenerator class with desired augmentation techniques:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
data_gen = ImageDataGenerator(
    rotation_range=15,                # randomly rotate images by 15 degrees
    width_shift_range=0.1,            # randomly shift images horizontally by 10%
    height_shift_range=0.1,           # randomly shift images vertically by 10%
    shear_range=0.2,                  # randomly apply shear transformation by 20%
    zoom_range=0.2,                   # randomly zoom images by 20%
    horizontal_flip=True,             # randomly flip images horizontally
    vertical_flip=False,              # do not randomly flip images vertically
    fill_mode='nearest'               # fill empty pixels with the nearest available pixel value
)


  1. Load your dataset using TensorFlow's image dataset class:
1
2
3
4
5
6
7
8
dataset = tf.keras.preprocessing.image_dataset_from_directory(
    directory="/path/to/dataset/",
    validation_split=0.2,
    subset="training",
    seed=123,
    image_size=(256, 256),
    batch_size=32
)


  1. Apply data augmentation to your dataset using the flow() method of the ImageDataGenerator instance:
1
augmented_dataset = dataset.map(lambda x, y: (data_gen.flow(x, seed=42)[0], y))


Here, data_gen.flow(x, seed=42) generates augmented images for each batch of original images.

  1. Finally, train your model using the augmented dataset:
1
model.fit(augmented_dataset, epochs=10)


Remember to adjust the augmentation parameters according to your specific requirements.

Member

by emie , 8 months ago

@noemy.bosco 

These steps guide you through the process of implementing data augmentation in TensorFlow using the ImageDataGenerator class for image datasets. Make sure to customize the data augmentation parameters based on your dataset characteristics and training objectives.