【发布时间】:2021-04-05 21:46:09
【问题描述】:
我使用两个长度不等的数据集。
我的目标是为 datasetA 中的每个元素获取另一个 datasetB 中的元素。我尝试.take(1)(如图here)从datasetB 中获取单个元素,但重复调用.take(1) 不会提前数据集的内部计数,即它总是返回相同的元素;但我想每次都得到一个新元素。
我可以使用for element in datasetA: 遍历一个数据集,然后使用elementB = iterB.get_next() 使用内部的第二个数据集。这会在使用 iterB 时引发错误。
这是我正在使用的完整玩具代码:
datasetA = tf.data.Dataset.from_tensor_slices([1, 2, 3, 4, 5, 6])
datasetB = tf.data.Dataset.from_tensor_slices([11, 22, 33, 44])
iterB = iter(datasetB)
epochs = 5
for epoch in range(epochs):
print(f"Epoch {epoch}")
for element in datasetA:
print(element)
elementB = iterB.get_next()
print(elementB)
然后我继续:
for epoch in range(epochs):
print(f"Epoch {epoch}")
for element in datasetA:
print(element)
elementB = iterB.get_next_as_optional()
if not elementB.has_value():
iterB = iter(datasetB)
elementB = iterB.get_next_as_optional()
print(elementB.get_value())
这可行,但重新初始化 datasetB 的迭代器很麻烦。
我进一步发现的是这个for old TensorFlow,它使用TF操作重新初始化迭代器,不再可用。 this question 中也提到了这一点,这很有帮助,但没有让我找到 TF2.+ 解决方案。
我正在寻找一种从datasetA 和datasetB 中获取成对元素的优雅方法,其中datasetB 在使用时(自动)重复。
我不需要遍历组合数据集,除非较短的数据集通过重复“填充”到较长的数据集,然后我可以从数据集A 和 B 中的 A 和 B数据集B。
TL;DR: 想要对两个长度不等的数据集进行成对迭代,使用时重新启动较短的数据集。
【问题讨论】:
标签: python tensorflow iterator