Loading Images, Text & Audio from Disk
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
Keras ships four loaders in keras.utils that cover the most common "files in folders" and "array of measurements" layouts. They return ready-to-train, batched datasets, so a first model needs no hand-written input code. This page documents each loader’s arguments and returned shapes, how the train/validation split works, and what to do when you outgrow them. The datasets are tf.data.Dataset objects, so everything on Input Pipelines with tf.data & TFRecord and tf.data Performance applies afterwards. Normalization and augmentation as model layers are on Keras Preprocessing Layers, and complete image and text models are on Image Classification with CNNs and Text, RNNs & Embeddings.
It targets Python 3.13, TensorFlow 2.21 with Keras 3.15 (TensorFlow 2.22 is upcoming; PyTorch 2.15 and scikit-learn 1.9 are mentioned for comparison) and was checked against the official keras.io API pages on 2026-10-30. Examples were run on Python 3.13 with TensorFlow 2.21 and Keras 3.15 (CPU) on 2026-10-31, on small synthetic image, text and WAV folders with the layouts shown; the signature listings match inspect.signature of the installed functions. Since TensorFlow 2.16, the spellings tf.keras.utils.image_dataset_from_directory and tf.keras.preprocessing.image_dataset_from_directory found in older tutorials both resolve to the same Keras 3 function as keras.utils.image_dataset_from_directory; in new code write keras.utils.*.
Directory layout and labels
The three directory loaders share one convention: with labels="inferred" (the default), each immediate sub-directory of directory is a class, and the files inside it are its samples. Class names are the sub-directory names in alphanumeric order, and the integer label is the index in that order.
data/
train/
cats/ cat001.jpg cat002.jpg ...
dogs/ dog001.jpg dog002.jpg ...
Other shared arguments:
| Argument | Meaning |
|---|---|
|
|
|
|
|
explicit list of class names, only with |
|
default 32; |
|
default |
|
seed for shuffling and for the validation split |
|
see the next section |
|
follow symbolic links to sub-directories, default |
|
print the number of files and classes found |
|
|
Which loss pairs with which label_mode is covered in Losses.
Train and validation splits
Pass validation_split (a fraction between 0 and 1) and subset ("training", "validation", or "both") together, with the same seed and validation_split in each call, so the two subsets partition the files without overlap.
import keras
common = dict(
directory="data/train",
validation_split=0.2,
seed=123,
image_size=(180, 180),
batch_size=32,
)
train_ds = keras.utils.image_dataset_from_directory(subset="training", **common)
val_ds = keras.utils.image_dataset_from_directory(subset="validation", **common)
# or in one call:
train_ds, val_ds = keras.utils.image_dataset_from_directory(subset="both", **common)
print(train_ds.class_names) # ['cats', 'dogs']
subset="both" returns a (train, validation) tuple from a single directory scan. The split is by file, taken after a seeded shuffle, and is not stratified, so a very small or very unbalanced class can end up under-represented in the validation set. Giving subset without validation_split (or the reverse) raises a ValueError stating that if subset is set, validation_split must be set, and inversely; supply both or neither. Test data should be a separate directory that you never use for choices. If the same underlying item appears in several files (augmented copies, near duplicates), split by item before writing the folders, otherwise validation leaks training data (see Generalization and Regularization).
Keep class_names on the dataset before further transforms: map, batch and prefetch return plain Dataset objects without that attribute.
Images
keras.utils.image_dataset_from_directory(
directory,
labels="inferred",
label_mode="int",
class_names=None,
color_mode="rgb",
batch_size=32,
image_size=(256, 256),
shuffle=True,
seed=None,
validation_split=None,
subset=None,
interpolation="bilinear",
follow_links=False,
crop_to_aspect_ratio=False,
pad_to_aspect_ratio=False,
data_format=None,
format="tf",
verbose=True,
)
It reads JPEG, PNG, BMP and GIF (the first frame) files and resizes every image to image_size (height, width), so batches are rectangular. It yields (images, labels) where images has shape (batch, height, width, channels) in float32 with raw pixel values 0 to 255, not scaled to 0 to 1, and labels has the shape given by label_mode. With label_mode=None it yields only the images.
Image-specific arguments:
-
color_mode:"rgb"(3 channels, the default),"grayscale"(1) or"rgba"(4). -
image_size: the target(height, width); the default is(256, 256), and the resize happens at load time, which costs CPU. Choose the size the model expects. -
interpolation: resize method, for example"bilinear"(default),"nearest","bicubic","area". -
crop_to_aspect_ratio: ifTrue, crop the largest centred window with the target aspect ratio and then resize, which keeps proportions but discards edges. IfFalse(default), the image is stretched to the target size and distorted. -
pad_to_aspect_ratio: ifTrue, pad with black borders to preserve the whole image instead of cropping. The two options are mutually exclusive, and the official page describes them as alternatives to stretching. -
data_format:"channels_last"or"channels_first";Nonefollows the Keras setting fromkeras.config.image_data_format().
import keras
import tensorflow as tf
from keras import layers
train_ds, val_ds = keras.utils.image_dataset_from_directory(
"data/train",
validation_split=0.2, subset="both", seed=1,
image_size=(160, 160), batch_size=64,
crop_to_aspect_ratio=True,
label_mode="categorical",
)
num_classes = len(train_ds.class_names)
AUTOTUNE = tf.data.AUTOTUNE
train_ds = train_ds.cache().shuffle(1000).prefetch(AUTOTUNE)
val_ds = val_ds.cache().prefetch(AUTOTUNE)
model = keras.Sequential([
keras.Input((160, 160, 3)),
layers.Rescaling(1 / 255.0), # 0-255 to 0-1, inside the model
layers.RandomFlip("horizontal"), # active only in training
layers.Conv2D(32, 3, activation="relu"),
layers.GlobalAveragePooling2D(),
layers.Dense(num_classes, activation="softmax"),
])
model.compile("adam", "categorical_crossentropy", metrics=["accuracy"])
# model.fit(train_ds, validation_data=val_ds, epochs=5)
Note the order: cache after the loader (decoding and resizing are deterministic) and before randomness; augmentation lives in the model as layers so it runs on the accelerator and only during training. The loader already shuffles files each epoch, so the extra shuffle(1000) only mixes within the cached stream and is optional. Putting Rescaling in the model means exported models accept raw pixels.
Limits: every image is decoded through TensorFlow’s image ops, so corrupt or unsupported files raise at iteration time rather than at construction; scan or filter files beforehand. Directories with millions of files are slow to list; switch to sharded TFRecords (see Input Pipelines with tf.data & TFRecord). For images listed in a CSV, build a dataset of paths and labels and map a decode function. The convolution background is in Convolutional Neural Networks.
Text
keras.utils.text_dataset_from_directory(
directory,
labels="inferred",
label_mode="int",
class_names=None,
batch_size=32,
max_length=None,
shuffle=True,
seed=None,
validation_split=None,
subset=None,
follow_links=False,
format="tf",
verbose=True,
)
It reads .txt files, one sample per file, from one sub-directory per class. Each batch is (texts, labels), where texts is a string tensor of shape (batch,) and labels follows label_mode. max_length truncates each text to that many characters. With format="grain" the texts are lists of Python strings instead of tensors.
import keras
import tensorflow as tf
train_ds, val_ds = keras.utils.text_dataset_from_directory(
"aclImdb/train", batch_size=32, validation_split=0.2, subset="both", seed=42,
)
for texts, labels in train_ds.take(1):
print(texts.shape, labels.shape) # (32,) (32,)
print(texts[0].numpy()[:80], labels[0].numpy())
vectorize = keras.layers.TextVectorization(
max_tokens=20_000, output_mode="int", output_sequence_length=256,
)
vectorize.adapt(train_ds.map(lambda text, label: text)) # learn the vocabulary
train_vec = train_ds.map(lambda t, y: (vectorize(t), y)).prefetch(tf.data.AUTOTUNE)
TextVectorization turns strings into integer ids and is covered on Keras Preprocessing Layers; call adapt on the training split only. The layer can also be placed inside the model so that it accepts raw strings. A string dataset element is a byte string, so call .numpy().decode("utf-8") to get Python text. The files are read as text and are not tokenized or cleaned by the loader.
Audio
keras.utils.audio_dataset_from_directory(
directory,
labels="inferred",
label_mode="int",
class_names=None,
batch_size=32,
sampling_rate=None,
output_sequence_length=None,
ragged=False,
shuffle=True,
seed=None,
validation_split=None,
subset=None,
follow_links=False,
verbose=True,
)
Only .wav files are supported. A batch is (audio, labels) with audio of shape (batch, sequence_length, num_channels); with label_mode=None only the raw file contents are yielded as strings. The audio-specific arguments:
-
sampling_rate: if set, audio is resampled to that rate (in Hz); ifNone, the files' rates are left as they are, so mixed rates give mixed time scales. -
output_sequence_length: the length, in samples, to which each clip is truncated or zero-padded, so batches are rectangular. IfNone, clips keep their own lengths and the loader pads to the longest clip in each batch, so lengths can vary between batches (with clips of 12,000 to 15,600 samples andbatch_size=4, the batches came out as 13,200, 14,800 and 15,600 samples long). -
ragged: ifTrue, return ragged batches, and the length is not padded (see Ragged & Sparse Tensors).
import keras
import tensorflow as tf
train_ds, val_ds = keras.utils.audio_dataset_from_directory(
"mini_speech_commands",
batch_size=64,
validation_split=0.2, subset="both", seed=0,
output_sequence_length=16_000, # one second at 16 kHz
)
print(train_ds.class_names)
def squeeze(audio, labels):
return tf.squeeze(audio, axis=-1), labels # mono: drop the channel axis
train_ds = train_ds.map(squeeze, tf.data.AUTOTUNE)
For spectrogram models, compute tf.signal.stft (or a Keras audio preprocessing layer if you use one) in a map and feed the result to a CNN. Other audio formats must be converted to WAV beforehand or decoded with another library. For the PyTorch counterpart see torchaudio and TorchCodec.
Time series from arrays
timeseries_dataset_from_array creates windows from arrays already in memory; there are no files or directories.
keras.utils.timeseries_dataset_from_array(
data,
targets,
sequence_length,
sequence_stride=1,
sampling_rate=1,
batch_size=128,
shuffle=False,
seed=None,
start_index=None,
end_index=None,
format="tf",
)
-
data: array or eager tensor; axis 0 is time. -
targets: aligned withdata:targets[i]is the target of the window that starts at indexi. PassNoneto get inputs only (for example for autoencoding or for building targets yourself). -
sequence_length: timesteps per window. -
sequence_stride: gap between the starts of successive windows (default 1, fully overlapping). -
sampling_rate: spacing between timesteps inside a window (default 1); with ratera window covers aboutsequence_length * rraw steps. -
start_index,end_index: use only part of the array, which is how you reserve chronological train, validation and test regions. -
shuffledefaults toFalse; windows come in time order unless enabled.
import numpy as np
series = np.arange(100, dtype="float32")[:, None] # 100 timesteps, 1 feature
# Predict the value 5 steps after each 10-step window.
past, horizon = 10, 5
inputs = series[:-horizon]
targets = series[past + horizon - 1:]
ds = keras.utils.timeseries_dataset_from_array(
inputs, targets, sequence_length=past, batch_size=16,
)
x, y = next(iter(ds))
print(x.shape, y.shape) # (16, 10, 1) (16, 1)
print(x[0, :, 0].numpy(), y[0].numpy()) # [0 ... 9] [14]
The target array is shifted so that targets[i] is the value that follows window i by the chosen horizon, here i + 10 + 5 - 1. The final windows that would run past the end are dropped, so the number of windows is fewer than the number of timesteps; the official example shows the last two points of a 99-point series being dropped when sequence length 10, sampling rate 2 and stride 3 are used.
Do not shuffle across the boundary between training and validation periods: use start_index and end_index, or separate slices of the array, and normalize with statistics from the training period only. For forecasting background see Recurrent Networks and Sequences; related array tools are in NumPy array creation.
When these loaders are not enough
-
Many small files or remote storage: shard to TFRecord.
-
Labels in a CSV or metadata file: build a dataset of paths and labels and
mapa decode function. -
Multimodal or nested records: build with
tf.dataand dictionaries. -
A curated public dataset: use TensorFlow Datasets.
-
Pre-trained backbones need their own preprocessing (see Transfer Learning & Fine-Tuning).
-
On non-TensorFlow backends,
format="grain"avoids the TensorFlow dependency for loaders that offer it; the multi-backend story is on Keras Multi-Backend.
Common mistakes
-
Forgetting that images arrive in the range 0 to 255 and that the default dtype is
float32; rescale in the model. -
Not passing the same
seedandvalidation_splitto the training and validation calls, which makes the subsets overlap. -
Reading
class_namesfrom a dataset aftermap/batch, when the attribute is gone. -
Assuming the label order is by folder creation time; it is alphanumeric unless
class_namesis given. -
Using
label_mode="binary"with more than two classes. -
Mismatching label mode and loss, for example
"categorical"labels withsparse_categorical_crossentropy. -
Shuffling a time series across train and validation periods.
-
Passing non-WAV audio.