python - 为什么 `tf.data.Dataset.map`只运行一次?

标签 python tensorflow tensorflow-datasets tensorflow2.0

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

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)

关于python - 为什么 `tf.data.Dataset.map`只运行一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56426839/

相关文章:

python - 我如何连接到 presto pyhive?

python - 如何在Python中对列表进行排序?

python - 执行 tf.train.example 时,出现 TypeError : 71 has type int, 但应为以下之一:bytes

tensorflow - 我可以将层归一化与 CNN 结合使用吗?

Python、asyncore、asynchat、Python 2.7.3 Mac 上的错误 错误的文件描述符

python - spidev/Python 错误

python - Bert 嵌入层使用 BiLSTM 引发 `Type Error: unsupported operand type(s) for +: ' None Type' 和 'int' `

python - 如何将序列输入 TensorFlow Keras 模型?

python - 如何在 TensorFlow 中使用 "group_by_window"函数

python - 使用 TF 数据集和 Eager 创建有状态计数器