如何将两个 tf.data.Dataset 合并为一个具有已知比率的交替元素

the*_*ony 2 python dataset tensorflow

我有两个 tf.data.Dataset,让我们调用它们d1,并且d2我想构造另一个包含d1d2交替元素的数据集。用一个例子更容易解释。让我们说:

d1 = [0,1,2,3,4,5,6,7,...] # it is not a list, just the content of the dataset

d2 = ["a", "b", "c", "d",... ]
Run Code Online (Sandbox Code Playgroud)

我让这对夫妇指定每个数据集中连续元素的数量(例如(3,1))。

我正在寻找的结果是:

result = [0, 1, 2, "a", 3, 4, 5, "b", 6, 7, 8, "c"...]
Run Code Online (Sandbox Code Playgroud)

编辑:d1 和 d2 是 tf.data.Dataset 类的对象。上面的示例仅显示了数据集的内容,但它不是代码。

小智 5

假设 TF 2.0。该技巧基于批处理,然后是数据集交错和取消批处理

import tensorflow as tf 

# input datasets
d1 = tf.data.Dataset.from_tensors([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]).unbatch()
d2 = tf.data.Dataset.from_tensors([100, 101, 102]).unbatch()
# replaced letters with numbers to make tensor types match

# define ratio
r1 = 3
r2 = 1

b1 = d1.batch(r1)
b2 = d2.batch(r2)

zipped = tf.data.Dataset.zip((b1, b2)).map(lambda x, y: tf.concat((x, y), axis=0))
result = zipped.unbatch()
Run Code Online (Sandbox Code Playgroud)

输出:

In [9]: list(result)                                                                                                                  
Out[9]: 
[<tf.Tensor: id=224, shape=(), dtype=int32, numpy=0>,
 <tf.Tensor: id=225, shape=(), dtype=int32, numpy=1>,
 <tf.Tensor: id=226, shape=(), dtype=int32, numpy=2>,
 <tf.Tensor: id=227, shape=(), dtype=int32, numpy=100>,
 <tf.Tensor: id=228, shape=(), dtype=int32, numpy=3>,
 <tf.Tensor: id=229, shape=(), dtype=int32, numpy=4>,
 <tf.Tensor: id=230, shape=(), dtype=int32, numpy=5>,
 <tf.Tensor: id=231, shape=(), dtype=int32, numpy=101>,
 <tf.Tensor: id=232, shape=(), dtype=int32, numpy=6>,
 <tf.Tensor: id=233, shape=(), dtype=int32, numpy=7>,
 <tf.Tensor: id=234, shape=(), dtype=int32, numpy=8>,
 <tf.Tensor: id=235, shape=(), dtype=int32, numpy=102>]
Run Code Online (Sandbox Code Playgroud)

注意:d1此解决方案可能会删除or末尾的一些元素d2- 它们的长度必须调整为比例。