0
0
TensorFlowml~5 mins

Data augmentation for images in TensorFlow

Choose your learning style9 modes available
Introduction

Data augmentation helps create more training images by changing existing ones. This makes models better at understanding new pictures.

When you have a small number of images to train your model.
To make your model recognize objects from different angles or lighting.
To reduce overfitting by showing varied images during training.
When you want to improve model accuracy without collecting more data.
Syntax
TensorFlow
import tensorflow as tf
from tensorflow.keras import layers

augmentation = tf.keras.Sequential([
    layers.RandomFlip('horizontal'),
    layers.RandomRotation(0.1),
    layers.RandomZoom(0.1),
])

augmented_images = augmentation(original_images, training=True)

Use tf.keras.Sequential to stack augmentation layers.

Apply augmentation only on training data, not on validation or test data.

Examples
Flips images left to right randomly.
TensorFlow
layers.RandomFlip('horizontal')
Rotates images randomly by up to 0.2 radians (about 11 degrees).
TensorFlow
layers.RandomRotation(0.2)
Zooms images in or out randomly by 10%.
TensorFlow
layers.RandomZoom(height_factor=0.1, width_factor=0.1)
Sample Model

This code creates two random images and applies flipping, rotation, and zoom. It prints the shapes to show images are unchanged in size.

TensorFlow
import tensorflow as tf
from tensorflow.keras import layers
import numpy as np

# Create a batch of 2 dummy images (32x32 RGB)
original_images = np.random.rand(2, 32, 32, 3).astype('float32')

# Define augmentation pipeline
augmentation = tf.keras.Sequential([
    layers.RandomFlip('horizontal'),
    layers.RandomRotation(0.1),
    layers.RandomZoom(0.1),
])

# Apply augmentation
augmented_images = augmentation(original_images, training=True)

# Print shapes to confirm augmentation
print('Original shape:', original_images.shape)
print('Augmented shape:', augmented_images.shape)
OutputSuccess
Important Notes

Augmentation layers work only during training by default.

You can customize augmentation intensity by changing parameters.

Augmentation helps models generalize better to new images.

Summary

Data augmentation creates new images by changing existing ones.

Use TensorFlow augmentation layers like RandomFlip, RandomRotation, and RandomZoom.

Apply augmentation only on training data to improve model learning.