How do you load, label, and feed jpeg data into Tensorflow?
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
Introduction
Before a neural network can learn from images, those images must be loaded from disk, decoded into numerical tensors, resized to a uniform shape, and paired with their labels. TensorFlow provides several APIs that handle this pipeline efficiently, from low-level file I/O to high-level directory loaders. This article shows you three progressively higher-level approaches so you can pick the one that matches your project's complexity.
Low-Level Loading with tf.io and tf.image
The most explicit way to load a JPEG is to read the raw bytes with tf.io.read_file and decode them with tf.image.decode_jpeg. This gives you full control over every preprocessing step.
You then combine this function with a tf.data.Dataset built from your file paths and labels.
num_parallel_calls=tf.data.AUTOTUNE lets TensorFlow decide how many images to decode in parallel, and prefetch ensures the next batch is being prepared while the GPU trains on the current one.
High-Level Loading with image_dataset_from_directory
If your images are organized in folders where each subfolder name is the class label, tf.keras.utils.image_dataset_from_directory handles loading, labeling, batching, and resizing in a single call.
This utility infers labels from the folder names, splits training and validation sets, and returns a tf.data.Dataset ready for model.fit(). For most classification tasks this is the fastest way to get started.
Building a Custom Dataset with Labels from a CSV
Sometimes labels live in an external file (a CSV, a database, or a JSON manifest) rather than in the directory structure. In that case you can build the file-path-to-label mapping yourself and feed it into a tf.data.Dataset.
This pattern is flexible enough to handle multi-label classification, regression targets, or any labeling scheme that does not map neatly to a folder hierarchy.
Adding Data Augmentation
Once your dataset pipeline is in place, you can insert augmentation layers to improve generalization. TensorFlow's Keras preprocessing layers run on the GPU and integrate directly into the pipeline.
Apply augmentation only to the training set. Validation and test sets should use the original, unmodified images so your metrics reflect real-world performance.
Common Pitfalls
- Forgetting to normalize pixel values: JPEG pixels range from 0 to 255. Feeding raw values into a model with small initial weights produces enormous activations and unstable training. Always rescale to [0, 1] or [-1, 1].
- Mismatched image sizes: If you skip
tf.image.resize, images of different dimensions will cause a shape error when TensorFlow tries to batch them. Every image in a batch must have the same height and width. - Using
shufflewith a buffer that is too small:tf.data.Dataset.shuffle(buffer_size=10)only shuffles within a window of 10 elements, which can leave the dataset nearly sorted. Set the buffer size to at least the number of samples in your dataset for a true shuffle. - Applying augmentation to validation data: Random flips, rotations, and zooms should only be applied during training. Augmenting validation data gives you noisy metrics that do not reflect real inference performance.
- Decoding PNGs with
decode_jpeg:tf.image.decode_jpegwill throw an error on PNG files. If your dataset contains mixed formats, usetf.image.decode_imageinstead, which auto-detects the format.
Summary
- Use
tf.io.read_fileandtf.image.decode_jpegfor full control over the loading and preprocessing pipeline. - Use
tf.keras.utils.image_dataset_from_directorywhen your images are organized in class-named subfolders for quick setup. - Build a custom
tf.data.Datasetfrom file paths and a CSV or manifest file when labels are stored externally. - Chain
.shuffle(),.batch(), and.prefetch(tf.data.AUTOTUNE)to keep the GPU fed efficiently during training. - Normalize pixel values and apply data augmentation only to the training split, never to validation or test data.
Related reading
- How do you load, label, and feed jpeg data into Tensorflow?
- How do you make TensorFlow Keras fast with a TFRecord dataset?
- How do you make TensorFlow Keras fast with a TFRecord dataset?
- How do you read Tensorboard files programmatically?
- How does 3D collision / object detection work?
- How does one convert 16-bit RGB565 to 24-bit RGB888?
- How do you locally load model.tar.gz file from Sagemaker?
- How do you read Tensorboard files programmatically?
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.