tensorflowtensorflow-estimatortf.data.dataset

Tensorflow Estimator: Samples using weighted distribution (probability)


I want to sample datas using weighted distribution (probability)

The examples are like below:

class distribution: doc_distribution = {0: 40, 1: 18, 2: 8, 3: 598, ... , 9: 177}

I would to make the batch of dataset by equal probability of class.

total_dataset = 0
init_dist = []
for value in doc_distribution.values():
  total_dataset += value
for value in doc_distribution.values():
  init_dist.append(value / total_dataset)
target_dist = []
for value in doc_distribution.values():
  target_dist.append(1 / len(doc_distribution))

Then, I make input_fn of tf.estimator to export the model,

def input_fn(ngram_words, labels, opts):
  dataset = tf.data.Dataset.from_tensor_slices((ngram_words, labels))
  rej = tf.data.experimental.rejection_resample(class_func = lambda _, c : c, \
    target_dist = target_dist, initial_dist = init_dist, seed = opts.seed)
  dataset = dataset.shuffle(buffer_size = len(ngram_words) * 2, seed = opts.seed)
  return dataset.batch(20)

Finally, I could get the result of rejection_resample as below:

for next_elem in a:
  k = next_elem[1]
  break
dist = {}
for val in np.array(k):
  if val in dist:
    dist[val] += 1
  else:
    dist[val] = 1
print(dist)

The result is: {3: 33, 8: 14, 4: 17, 7: 5, 5: 10, 9: 12, 0: 6, 6: 3}

I don't know why rejection_resample doesn't work well, I just want to extract samples equally. How should I fix it?

Is there any methods to sample equally in input_fn of tf.estimator?


Solution

  • We can use tf.data.experimental.sample_from_datasets instead of rejection_resample.

    unbatched_dataset = [(dataset.filter(lambda _, label: label == i)) for i in range(0, classify_num)]
    weights = [1 / classify_num] * classify_num
    balanced_ds = tf.data.experimental.sample_from_datasets(unbatched_dataset, weights, seed=opts.seed)
    dataset = balanced_ds.shuffle(buffer_size = 1000, seed = opts.seed).repeat(opts.epochs)