RandAugment for Image Classification Keras for Robustness

Implementing RandAugment for Image Classification Keras is one of the best ways I have found to boost model robustness without the headache of manual hyperparameter tuning.

I have spent many late nights adjusting individual augmentation values only to find that a simple, automated strategy like RandAugment often yields much better results for real-world applications.

In this guide, I will share my firsthand experience using three different methods to implement this in Python.

Method 1: Use KerasCV RandAugment Layer

This is my go-to method because it is built directly into the modern Keras ecosystem and integrates seamlessly with existing training pipelines.

import os
os.environ["KERAS_BACKEND"] = "tensorflow"
import keras
import keras_cv
import tensorflow as tf

# I usually use a standard American dataset like Caltech-101 or flowers
# Let's set up a RandAugment layer for a furniture classification task in a Chicago warehouse
rand_augment = keras_cv.layers.RandAugment(
    value_range=(0, 255),
    augmentations_per_image=3,
    magnitude=0.8
)

def apply_randaugment_keras(image, label):
    # I always cast to uint8 before applying RandAugment for best results
    image = tf.cast(image, tf.uint8)
    return rand_augment(image), label

# Usage with a tf.data pipeline
# train_ds = train_ds.map(apply_randaugment_keras)
dummy_image = tf.random.uniform((224, 224, 3), minval=0, maxval=255, dtype=tf.int32)
dummy_label = 0

# Apply RandAugment
aug_image, aug_label = apply_randaugment_keras(dummy_image, dummy_label)

# Print outputs
print("Augmented image shape:", aug_image.shape)
print("Label:", aug_label)
print("Sample pixel values:", aug_image[0, 0])

I executed the above example code and added the screenshot below.

RandAugment for Image Classification in Keras

I find that using the keras_cv implementation is the most efficient way to apply high-performance augmentations like solarization and shearing with just one line of code.

Method 2: Custom RandAugment Implementation via Keras Preprocessing

When I need more control over which specific operations are included in the pool, I build a custom pipeline using standard Keras preprocessing layers.

from keras import layers

def get_custom_randaugment_keras():
    # I select a subset of layers that make sense for regional traffic data
    augment_pool = [
        layers.RandomFlip("horizontal"),
        layers.RandomRotation(0.15),
        layers.RandomContrast(0.2),
        layers.RandomTranslation(height_factor=0.1, width_factor=0.1),
        layers.RandomZoom(0.2)
    ]
    
    # In my experience, choosing 2 random layers works best for stability
    import random
    selected_layers = random.sample(augment_pool, 2)
    return keras.Sequential(selected_layers)

# Applying the custom sequence to a batch of images
# custom_aug = get_custom_randaugment_keras()
# augmented_images = custom_aug(input_images)
input_images = tf.random.uniform(
    shape=(2, 224, 224, 3),
    minval=0,
    maxval=255,
    dtype=tf.float32
)

# Apply custom augmentation
custom_aug = get_custom_randaugment_keras()
augmented_images = custom_aug(input_images)

# Print outputs
print("Input shape:", input_images.shape)
print("Augmented shape:", augmented_images.shape)
print("Sample pixel values (before):", input_images[0, 0, 0])
print("Sample pixel values (after):", augmented_images[0, 0, 0])

I executed the above example code and added the screenshot below.

RandAugment for Image Classification Keras

This approach is ideal when your specific dataset (such as San Francisco street signs) doesn’t benefit from certain extreme distortions, like vertical flipping.

Method 3: Script RandAugment with tf.image and Python

Sometimes I work on legacy systems where I cannot install extra packages like KerasCV, so I implement a lightweight version using tf.image.

import tensorflow as tf

def randaugment_tf_image_keras(image, magnitude=10):
    # I often use a magnitude-based approach to scale the intensity
    # Here we randomly choose between brightness and saturation
    if tf.random.uniform([]) > 0.5:
        image = tf.image.random_brightness(image, max_delta=magnitude / 100.0)
    else:
        image = tf.image.random_saturation(image, lower=0.5, upper=1.5)
        
    image = tf.image.random_flip_left_right(image)
    return tf.clip_by_value(image, 0, 255)

# Integration into a mapping function for Keras training
def preprocess_data_keras(image, label):
    image = randaugment_tf_image_keras(image)
    return image, label
dummy_image = tf.random.uniform(
    shape=(224, 224, 3),
    minval=0,
    maxval=255,
    dtype=tf.float32
)
dummy_label = tf.constant(1)

# Apply preprocessing
aug_image, aug_label = preprocess_data_keras(dummy_image, dummy_label)

# Print outputs
print("Original image shape:", dummy_image.shape)
print("Augmented image shape:", aug_image.shape)
print("Original pixel value:", dummy_image[0, 0])
print("Augmented pixel value:", aug_image[0, 0])
print("Label:", aug_label)

I executed the above example code and added the screenshot below.

RandAugment for Image Classification Keras for Robustness

In this tutorial, I have shown you how to implement RandAugment using three different strategies. Each method has its own benefits depending on your project’s specific needs and environment.

I hope you find these examples helpful for your next image classification project.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.