我希望程序可以
x
复制tf.identity
的旧值,y
分配给x
但是tf.identity
并没有保留x
的旧值。
tf.control_dependencies
应该要求在执行步骤2之前执行步骤1。
结果:
version: 1.14.1-dev20190531
x_before_: 0.0
x_ident_: 1.0
x_after_: 1.0
测试:
import numpy as np
import tensorflow as tf
dtype = np.float32
x = tf.get_variable('x', shape=(), dtype=dtype,
initializer=tf.zeros_initializer)
y = tf.constant(1, dtype=dtype)
# Copy value of x before assigning new value y to x
x_ident = tf.identity(x)
with tf.control_dependencies([x_ident]):
assign_op = tf.assign(x, y)
# Run
init_op = x.initializer
with tf.Session() as sess:
sess.run(init_op)
x_before_ = sess.run(x)
x_ident_ = sess.run([x_ident, assign_op])[0]
x_after_ = sess.run(x)
# Check
print("version:", tf.__version__)
print("x_before_:", x_before_)
print("x_ident_:", x_ident_)
print("x_after_:", x_after_)
assert np.allclose(x_ident_, 0)
答案 0 :(得分:2)
我过去曾发现此问题,我认为您是对的,它应该可以按预期工作。也许值得filing an issue。我没有这样的解决方案,但是我的解决方法是进行无用的操作,例如添加零:
import numpy as np
import tensorflow as tf
dtype = np.float32
x = tf.get_variable('x', shape=(), dtype=dtype,
initializer=tf.zeros_initializer)
y = tf.constant(1, dtype=dtype)
# Force snapshot of x with zero addition
x_ident = x + 0
with tf.control_dependencies([x_ident]):
assign_op = tf.assign(x, y)
# Run
init_op = x.initializer
with tf.Session() as sess:
sess.run(init_op)
x_before_ = sess.run(x)
x_ident_ = sess.run([x_ident, assign_op])[0]
x_after_ = sess.run(x)
# Check
print("version:", tf.__version__)
print("x_before_:", x_before_)
print("x_ident_:", x_ident_)
print("x_after_:", x_after_)
assert np.allclose(x_ident_, 0)
输出:
version: 1.14.0
x_before_: 0.0
x_ident_: 0.0
x_after_: 1.0