image_dataset_from_directory constructs an image dataset from files arranged in directories. It finds class subdirectories, indexes their images, decodes JPEG files, resizes them, shuffles them, and returns batches suitable for a Keras model. section 8.2.4
Create training, validation, and test datasets
image_size <- shape(180, 180) batch_size <- 32 train_dataset <- image_dataset_from_directory(new_base_dir / "train", image_size = image_size, batch_size = batch_size) validation_dataset <- image_dataset_from_directory(new_base_dir / "validation", image_size = image_size, batch_size = batch_size) test_dataset <- image_dataset_from_directory(new_base_dir / "test", image_size = image_size, batch_size = batch_size) Each directory contains class subdirectories. The resulting datasets can be passed directly to fit(). section 8.2.4
The utility automates the main preparation steps required before image data reaches a model:
- Reads image files from class-organized subdirectories and infers the classes from that organization. section 8.2.4
- Decodes JPEG content into RGB pixel grids and converts the images into tensors. section 8.2.4
- Resizes images to a shared size and packs them into batches, such as batches of 32 images. section 8.2.4
- Supports unlabeled image collections with labels = NULL and can preserve aspect ratio through crop_to_aspect_ratio = TRUE. section 17.2.1
Listing 8.9 Using image_dataset_from_directory() to read images from directories
image_size <- shape(180, 180)
batch_size <- 32
train_dataset <-
image_dataset_from_directory(new_base_dir / "train",
image_size = image_size,
batch_size = batch_size)
validation_dataset <-
image_dataset_from_directory(new_base_dir / "validation",
image_size = image_size,
batch_size = batch_size)
test_dataset <-
image_dataset_from_directory(new_base_dir / "test",
image_size = image_size,
batch_size = batch_size)
Use the complete listing to create separate datasets for training, validation, and testing. section 8.2.4
The returned object is a tf.data.Dataset: an iterable sequence of input batches and labels that can be inspected, transformed, and supplied directly to model training. section 8.2.4

