将多个 TensorFlow 数据集交织在一起

Interleaving multiple TensorFlow datasets together

当前的 TensorFlow 数据集交错功能基本上是一个以单个数据集作为输入的交错平面图。鉴于当前 API,将多个数据集交织在一起的最佳方式是什么?假设它们已经建成并且我有它们的清单。我想从它们中交替生成元素,并且我想支持包含 2 个以上数据集的列表(即,堆叠的拉链和交错会非常难看)。

谢谢! :)

@mrry 或许可以提供帮助。

编辑 2: 参见 tf.contrib.data.choose_from_datasets。它执行确定性数据集交错。

编辑: 参见 tf.contrib.data.sample_from_datasets。即使它执行随机抽样,我想它还是很有用的。


尽管这不是 "clean",但这是我想出的唯一解决方法。

datasets = [tf.data.Dataset...]

def concat_datasets(datasets):
    ds0 = tf.data.Dataset.from_tensors(datasets[0])
    for ds1 in datasets[1:]:
        ds0 = ds0.concatenate(tf.data.Dataset.from_tensors(ds1))
    return ds0

ds = tf.data.Dataset.zip(tuple(datasets)).flat_map(
    lambda *args: concat_datasets(args)
)

扩展 user2781994 (经过编辑),我是这样实现的:

import tensorflow as tf

ds11 = tf.data.Dataset.from_tensor_slices([1,2,3])
ds12 = tf.data.Dataset.from_tensor_slices([4,5,6])
ds13 = tf.data.Dataset.from_tensor_slices([7,8,9])
all_choices_ds = [ds11, ds12, ds13]

choice_dataset = tf.data.Dataset.range(len(all_choices_ds)).repeat()
ds14 = tf.contrib.data.choose_from_datasets(all_choices_ds, choice_dataset)

# alternatively:
# ds14 = tf.contrib.data.sample_from_datasets(all_choices_ds)

iterator = ds14.make_initializable_iterator()
next_element = iterator.get_next()

with tf.Session() as sess:
    sess.run(iterator.initializer)
    while True:
        try:
            value=sess.run(next_element)
        except tf.errors.OutOfRangeError:
            break
        print(value)

输出为:

1
4
7
2
5
8
3
6
9

在 Tensorflow 2.0 中

tot_imm_dataset1 = 105
tot_imm_dataset2 = 55
e = tf.data.Dataset.from_tensor_slices(tf.cast([1,0,1],tf.int64)).repeat(int(tot_imm_dataset1/2)) 
f=tf.data.Dataset.range(1).repeat(int(tot_imm_dataset2-tot_imm_dataset1/2))
choice=e.concatenate(f)
datasets=[dataset2,dataset1]
dataset_rgb_compl__con_patch= tf.data.experimental.choose_from_datasets(datasets, choice)

对我有用