为什么'tf.data.Dataset.map'只运行一次



我一直在挖掘。仍然让我感到困惑,我在任何地方都找不到明确的解释。

dataset1 = tf.data.Dataset.from_tensor_slices(([1]*20))
dataset1 = (dataset1
            .batch(4)
            .map(lambda x: x+random.randint(0,20)))
for batch in iter(dataset1):
  print(batch)
tf.Tensor([21 21 21 21], shape=(4,), dtype=int32)
tf.Tensor([21 21 21 21], shape=(4,), dtype=int32)
tf.Tensor([21 21 21 21], shape=(4,), dtype=int32)
tf.Tensor([21 21 21 21], shape=(4,), dtype=int32)
tf.Tensor([21 21 21 21], shape=(4,), dtype=int32)

我希望.map表现得像一个正常的功能性map。其中,它应该对每个元素应用一个函数。感觉我的一些假设完全不对。

你需要使用tf.random模块,因为原生python只会生成数字一次

dataset1 = tf.data.Dataset.from_tensor_slices(([1]*20))
dataset1 = (dataset1
            .batch(4)
            .map(lambda x: x+tf.random.uniform((), 0, 20, tf.int32)))
for batch in iter(dataset1):
    print(batch)

任何张量流声明都是执行图的声明,在您的情况下,必须通过 sess = tf.Session() , sess.run(object) , sess.run(dataset1 ( 额外运行

最新更新