how to access tf.data.Dataset within a keras custom callback?

1.4k views Asked by At

I have written a custom keras callback to check the augmented data from a generator. (See this answer for the full code.) However, when I tried to use the same callback for a tf.data.Dataset, it gave me an error:

  File "/path/to/tensorflow_image_callback.py", line 16, in on_batch_end
imgs = self.train[batch][images_or_labels]
TypeError: 'PrefetchDataset' object is not subscriptable

Do keras callbacks in general only work with generators, or is it something about the way I've written my one? Is there a way to modify either my callback or the dataset to make it work?

I think there are three pieces to this puzzle. I'm open to changes to any and all of them. Firstly, the init function in the custom callback class:

class TensorBoardImage(tf.keras.callbacks.Callback):
    def __init__(self, logdir, train, validation=None):
        super(TensorBoardImage, self).__init__()
        self.logdir = logdir
        self.file_writer = tf.summary.create_file_writer(logdir)
        self.train = train
        self.validation = validation

Secondly, the on_batch_end function within that same class

def on_batch_end(self, batch, logs):
    images_or_labels = 0 #0=images, 1=labels
    imgs = self.train[batch][images_or_labels]

Thirdly, instantiating the callback

import tensorflow_image_callback
tensorboard_image_callback = tensorflow_image_callback.TensorBoardImage(logdir=tensorboard_log_dir, train=train_dataset, validation=valid_dataset)
model.fit(train_dataset,
          epochs=n_epochs,
          validation_data=valid_dataset, 
          callbacks=[
                    tensorboard_callback,
                    tensorboard_image_callback
                    ])

Some related threads which haven't led me to an answer yet:

Accessing validation data within a custom callback

Create keras callback to save model predictions and targets for each batch during training

1

There are 1 answers

0
craq On

What ended up working for me was the following, using tfds:

the __init__ function:

def __init__(self, logdir, train, validation=None):
    super(TensorBoardImage, self).__init__()
    self.logdir = logdir
    self.file_writer = tf.summary.create_file_writer(logdir)
    # #from keras generator
    # self.train = train
    # self.validation = validation
    #from tf.Data
    my_data = tfds.as_numpy(train)
    imgs = my_data['image']

then on_batch_end:

def on_batch_end(self, batch, logs):
    images_or_labels = 0 #0=images, 1=labels
    imgs = self.train[batch][images_or_labels]

    #calculate epoch
    n_batches_per_epoch = self.train.samples / self.train.batch_size
    epoch = math.floor(self.train.total_batches_seen / n_batches_per_epoch)

    #since the training data is shuffled each epoch, we need to use the index_array to find something which uniquely 
    #identifies the image and is constant throughout training
    first_index_in_batch = batch * self.train.batch_size
    last_index_in_batch = first_index_in_batch + self.train.batch_size
    last_index_in_batch = min(last_index_in_batch, len(self.train.index_array))
    img_indices = self.train.index_array[first_index_in_batch : last_index_in_batch]

    with self.file_writer.as_default():
        for ix,img in enumerate(imgs):
            #only post 1 out of every 1000 images to tensorboard
            if (img_indices[ix] % 1000) == 0:
                #instead of img_filename, I could just use str(img_indices[ix]) as a unique identifier
                #but this way makes it easier to find the unaugmented image
                img_filename = self.train.filenames[img_indices[ix]]

                #convert float to uint8, shift range to 0-255
                img -= tf.reduce_min(img)
                img *= 255 / tf.reduce_max(img)
                img = tf.cast(img, tf.uint8)
                img_tensor = tf.expand_dims(img, 0) #tf.summary needs a 4D tensor
                
                tf.summary.image(img_filename, img_tensor, step=epoch)

I didn't need to make any changes to the instantiation.

I recommend only using it for debugging, otherwise it saves every nth image in your dataset to tensorboard every epoch. That can end up using a lot of disk space.