如何从具有相同标签的 Tensorflow 数据集中提取样本?

How to extract samples from a Tensorflow Dataset which have the same label?

我想通过以下方式从 TF 数据集中生成批处理样本:每个批处理将包含两个具有相同 'label' 特征的样本。在 Tensorflow 中实现此目的的最有效方法是什么?

假设您有一些带有多个标签的数据,如下所示:

x = tf.random.uniform((10, 2), maxval=20, dtype=tf.int32)
y = tf.random.uniform((10, ), maxval=4, dtype=tf.int32)
dataset = tf.data.Dataset.from_tensor_slices((x, y))

为了达到你的目的。 “每个批次将包含两个具有相同 'label' 特征的样本”,您可以使用 filter 函数为每个标签创建单独的数据集,然后 concatenate 函数 tf.data.Dataset API 将这些数据集合并为一个:

x = tf.random.uniform((10, 2), maxval=20, dtype=tf.int32)
y = tf.random.uniform((10, ), maxval=4, dtype=tf.int32)
dataset = tf.data.Dataset.from_tensor_slices((x, y))

batch_size = 2
dataset0 = dataset.filter(lambda x, y: tf.equal(y, 0)).batch(batch_size)
dataset1 = dataset.filter(lambda x, y: tf.equal(y, 1)).batch(batch_size)
dataset2 = dataset.filter(lambda x, y: tf.equal(y, 2)).batch(batch_size)
dataset3 = dataset.filter(lambda x, y: tf.equal(y, 3)).batch(batch_size)

dataset = dataset0.concatenate(dataset1).concatenate(dataset2).concatenate(dataset3).shuffle(buffer_size=20)