I have started using the tf.data.Dataset as a way to load data into keras models, as they appear to be much faster than keras' ImageDataGenerator and much more memory efficient than training on arrays.
One think I can't get my head around is that I can't seem to find a way to access the len() of the dataset. Keras' ImageDataGenerator has an attribute called n which I used to use for this purpose. This makes my code very ugly, as I need to hard-code the length in various parts of the scripy (e.g. to find out how many iterations an epoch has).
Any ideas I can work around this issue?
An example script:
# Generator
def make_mnist_train_generator(batch_size):
(x_train, y_train), (_,_) = tf.keras.mnist.load_data()
x_train = x_train.reshape((-1, 28, 28, 1))
x_train = x_train.astype(np.float32) / 225.
y_train = tf.keras.utils.to_categorical(y_train, 10)
ds = tf.data.Dataset.from_tensor_slices((x_train, y_train))
ds = ds.shuffle(buffer_size=len(x_train))
ds = ds.repeat()
ds = ds.batch(batch_size=batch_size)
ds = ds.prefetch(buffer_size=1)
return ds
model = ... # create a tf.keras model
batch_size 256
gen = make_mnist_train_generator(batch_size)
# Training
model.fit(gen, epochs=50, steps_per_epoch=60000//batch_size+1) # Hard coded size of generator