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
Loading JPEG images into TensorFlow involves reading image files, decoding them to tensors, resizing to a uniform shape, normalizing pixel values, associating labels, and batching into a tf.data.Dataset pipeline. The recommended approach is tf.keras.utils.image_dataset_from_directory, which handles all of these steps automatically when images are organized in label-named subdirectories. For custom loading, use tf.data.Dataset with tf.io.read_file and tf.io.decode_jpeg.
Method 1: image_dataset_from_directory (Recommended)
Organize images in directories named after their labels:
Normalize and Optimize the Pipeline
Method 2: Custom tf.data Pipeline
For images not organized in label directories:
Method 3: Loading from CSV with Labels
Data Augmentation
Apply random transformations to training images:
Training a Model with the Dataset
Handling Large Datasets
For datasets that do not fit in memory:
Common Pitfalls
- Not specifying
channels=3indecode_jpeg: Some JPEG files are grayscale (1 channel) or CMYK (4 channels). Withoutchannels=3, the tensor shape varies per image, causing batch errors. Always setchannels=3for RGB consistency. - Forgetting to normalize pixel values: Raw JPEG pixels range from 0 to 255. Neural networks train better with normalized inputs (0 to 1 or -1 to 1). Add
image / 255.0or usetf.keras.layers.Rescaling. - Images of different sizes without resizing: JPEGs come in various dimensions. Without
tf.image.resize, tensors cannot be batched together because shapes differ. Always resize to a uniform(height, width). - Shuffling after batching:
ds.batch(32).shuffle(100)shuffles batches, not individual samples. Place.shuffle()before.batch()for proper sample-level shuffling. - Loading all images into memory at once: Using
tf.io.read_fileinsideDataset.maploads images lazily. Avoid reading all images into a NumPy array first — that defeats the purpose of thetf.datapipeline and may cause out-of-memory errors.
Summary
- Use
tf.keras.utils.image_dataset_from_directoryfor the simplest loading when images are organized by label directories - Use
tf.data.Datasetwithtf.io.decode_jpegfor custom loading from file paths and labels - Always resize images to uniform dimensions and normalize pixel values before training
- Add
.cache().shuffle().prefetch(AUTOTUNE)for optimal pipeline performance - Use TFRecord format for large datasets that benefit from sequential read performance
Related reading
- 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 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 save a Tensorflow dataset to a file?
.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 courseNo course covers this one yet
Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.
Build my 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.