Here is my solution. To show how it works, I use cats/dogs datasets:
import matplotlib.pyplot as plt
import numpy as np
import os
import tensorflow as tf
_URL = 'https://storage.googleapis.com/mledu-datasets/cats_and_dogs_filtered.zip'
path_to_zip = tf.keras.utils.get_file('cats_and_dogs.zip', origin=_URL, extract=True)
PATH = os.path.join(os.path.dirname(path_to_zip), 'cats_and_dogs_filtered')
train_dir = os.path.join(PATH, 'train')
#'/Users/mustafamuratarat/.keras/datasets/cats_and_dogs_filtered/train'
BATCH_SIZE = 32
IMG_SIZE = (160, 160)
img_gen = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1./255)
gen = img_gen.flow_from_directory(train_dir, target_size=(160, 160), batch_size=32)
#<tensorflow.python.keras.preprocessing.image.DirectoryIterator at 0x7fb9fde3b250>
#gen.class_indices
#{'cats': 0, 'dogs': 1}
#gen.target_size
#(160, 160)
# gen.batch_size
# 32
# gen.num_classes
# 2
dataset = tf.data.Dataset.from_generator(
lambda: gen,
output_types = (tf.float32, tf.float32),
output_shapes = ([None, 160, 160, 3], [None, 2]),
)
#list(dataset.take(1).as_numpy_iterator())
Then you can feed dataset
object to any model.
generator
must be callable.'.tf.data.Dataset.from_generator(ImageDataGenerator().flow_from_directory('folder_path'), (tf.float32, tf.float32))
– Longanimity