打印内部和外部有什么区别



我正在学习tensorflow,我的MacBook M1上的版本是2.8.0。为了调试数据集map函数中的代码,我想在我的函数中打印张量值。

def function(i):
print("in: ", i)
if i < 2:
i = i - 1
return i

dataset = tf.data.Dataset.range(1, 6)
dataset = dataset.map(lambda x: tf.py_function(function, inp=[x], Tout=tf.int64))
for x in dataset:
print("out:", x)

我得到了错误的输出:

in:  tf.Tensor(1, shape=(), dtype=int64)
out: tf.Tensor(0, shape=(), dtype=int64)
in:  tf.Tensor(2, shape=(), dtype=int64)
out: tf.Tensor(2, shape=(), dtype=int64)
in:  tf.Tensor(3, shape=(), dtype=int64)
out: tf.Tensor(3, shape=(), dtype=int64)
in:  tf.Tensor(4, shape=(), dtype=int64)
out: tf.Tensor(4, shape=(), dtype=int64)
in:  tf.Tensor(5, shape=(), dtype=int64)
out: tf.Tensor(5, shape=(), dtype=int64)

我删除外面的打印后,我没有得到任何输出。里面的印花和外面的印花有什么区别?我不明白为什么只有当指纹同时出现时才能生效。除此之外,print和tf.print有什么区别?

我认为这是因为tensorflow数据集有延迟加载,这意味着它们不会被评估,直到你真正尝试遍历结果。

当你删除for循环时,你不再对结果进行迭代,所以它永远不会被求值。

见https://stackoverflow.com/a/54679387/494134

最新更新