Folder Structure
Keras can read images straight from folders. Each subfolder name becomes a class label.
text
photos/
cats/
cat001.jpg
cat002.jpg
dogs/
dog001.jpg
dog002.jpg
Load Training and Validation Data
python
import keras
from keras import layers
img_size = (180, 180)
batch_size = 32
train_ds = keras.utils.image_dataset_from_directory(
"photos",
validation_split=0.2,
subset="training",
seed=123,
image_size=img_size,
batch_size=batch_size,
)
val_ds = keras.utils.image_dataset_from_directory(
"photos",
validation_split=0.2,
subset="validation",
seed=123,
image_size=img_size,
batch_size=batch_size,
)
class_names = train_ds.class_names
print(class_names) # ['cats', 'dogs']
Use the same seed: Both calls must use the same seed and validation_split, otherwise the training and validation images could overlap.
Look at a Batch
python
import matplotlib.pyplot as plt
plt.figure(figsize=(8, 8))
for images, labels in train_ds.take(1):
for i in range(9):
plt.subplot(3, 3, i + 1)
plt.imshow(images[i].numpy().astype("uint8"))
plt.title(class_names[labels[i]])
plt.axis("off")
plt.show()
Speed Up the Pipeline
python
AUTOTUNE = tf.data.AUTOTUNE # import tensorflow as tf first
train_ds = train_ds.cache().shuffle(1000).prefetch(AUTOTUNE)
val_ds = val_ds.cache().prefetch(AUTOTUNE)
Rescale Inside the Model
Put the scaling inside the model with a Rescaling layer. Then the same preprocessing is automatically saved with the model.
python
model = keras.Sequential([
keras.Input(shape=(180, 180, 3)),
layers.Rescaling(1.0 / 255),
layers.Conv2D(32, 3, activation="relu"),
layers.MaxPooling2D(),
layers.Conv2D(64, 3, activation="relu"),
layers.MaxPooling2D(),
layers.Flatten(),
layers.Dense(64, activation="relu"),
layers.Dense(1, activation="sigmoid"),
])
For two classes use label_mode="binary" in image_dataset_from_directory with a sigmoid output, or use integer labels (the default) with a softmax output and sparse_categorical_crossentropy.
Useful Options
| Option | Meaning |
image_size | All images are resized to this size |
batch_size | Images per batch |
label_mode | int, categorical, binary or None |
color_mode | rgb, grayscale or rgba |
shuffle | Shuffle the files (default True) |
Tip: Before training, check that every class has a similar number of images. Very unbalanced folders lead to biased models.
Conclusion
With one function you can turn a folder of pictures into a fast, batched dataset. This is how most real image projects start.
Quick Summary: Use image_dataset_from_directory with matching seeds, then cache, shuffle and prefetch, and rescale inside the model.