python - tensorflow 中的 "y=x"和 y=tf.identity(x) 有什么区别

标签 python tensorflow

我对以下代码感到困惑:y = xy = tf.identity(x) 。 更准确地说,当我运行以下代码片段时,我感到困惑:

代码1:

import tensorflow as tf
x = tf.Variable(0.0, name="x")
with tf.control_dependencies([x_plus_1]):
    y = x
init = tf.initialize_all_variables()
with tf.Session() as sess:
    init.run()
    for i in range(5):
        print(y.eval())

这将给出输出:0.0 0.0 0.0 0.0 0.0

代码2:

import tensorflow as tf
x = tf.Variable(0.0, name="x")
with tf.control_dependencies([x_plus_1]):
    y = tf.identity(x, name='id')
init = tf.initialize_all_variables()

with tf.Session() as sess:
    init.run()
    for i in range(5):
        print(y.eval())

唯一的变化来自 y=xy=tf.identity(x) ,但现在结果是1.0 2.0 3.0 4.0 5.0

非常感谢。

最佳答案

x 是一个张量,我们称之为 tensor_1。当您说 y = x 时,您是在说变量 y 具有张量 tensor_1 的值。当您执行 y = tf.identity(x) 时,您将创建一个新的张量 tensor_2,其值与 tensor_1 相同。但它是图中的不同节点,因此从 tensor_1tensor_2 的值必须移动。这就是为什么 with tf.control_dependency([x_plus_1]) 在第二个代码中执行某些操作,但在第一个代码中执行任何操作。因为在第一个代码中,您没有创建 control_depdendency 可以使用的任何新张量。

综上所述,y = x 使变量 y 指向 x 中的同一个对象,但 y = tf .identity(x) 使用 x 的内容创建一个新对象。

关于python - tensorflow 中的 "y=x"和 y=tf.identity(x) 有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49880372/

相关文章:

python - Tensorflow 错误 : ValueError: Shapes must be equal rank, 但 2 和 1 来自合并形状 1 与其他形状

python - 如何使用非大写 p 的 TensorFlow tf.print?

python - 从命令行运行 R 脚本(从 python 执行)

python - 除了 `NoneType` 之外,Python 中还有什么是 `None` 吗?

python - 用多字符字母查找特定字母表中的所有单词

python - 使用 python requests 模块在 Github 中创建经过身份验证的 session

Tensorflow 对象检测 API eval.py - 分配前引用了 'metrics'

c++ - Mac OS X 上的 Boost.Python : "TypeError: Attribute name must be string"

python - 我想从 TFRecord 读取数据

tensorflow - 如何在 Keras 中为图像分割加载图像掩码(标签)