I have an image dataset with a large imbalance of positive and negatives samples (many more negatives). I would like to create a tf.data.Dataset where each epoch it will train with all of the positive samples but only (ratio * len(positive) ) of the negative samples.
I am currently using a datagen inherited from keras.util.Sequence to achieve this and using this subsampling policy is performing much better than training on all data.
However reading the docs on Dataset, I cannot seem to find a way to do it, is it possible?
In my existing data generator, I am doing this:
# List if indicies of the positive and negative samples
positives = np.where(self.labels == 1)[0]
negatives = np.where(self.labels == 0)[0]
# How many of the negatives do we want to use?
n_negatives = np.clip(int(len(positives) * self.config.DATASET_NEGSUBSAMPLE_RATIO), 1, len(negatives))
# Choose random negatives
subsampled_negatives = np.random.choice(negatives, n_negatives, replace=False)
# Create the incidies array from the positive and subsamples negative indicies
self.indexes = np.concatenate((positives, subsampled_negatives))
# Shuffle them together
np.random.shuffle(self.indexes)