如何在确保变量已经初始化的同时获取变量的当前值? tf.Variable.initialized_value()
依赖于初始化程序,导致每次访问变量时都会将变量重置为其初始值。为防止变量被重置,我尝试将tf.cond()
与tf.is_variable_initialized()
一起用作谓词。但是,这不起作用,因为条件的true分支需要初始化变量,即使false分支处于活动状态:
import tensorflow as tf
def once_initialized_value(variable):
return tf.cond(
tf.is_variable_initialized(variable),
lambda: variable.value(),
lambda: variable.initialized_value())
a = tf.Variable(42, name='a')
b = tf.Variable(once_initialized_value(a), name='b')
sess = tf.Session()
sess.run(tf.global_variables_initializer())
print(sess.run(b)) # Error: Attempting to use uninitialized value a
答案 0 :(得分:0)
在initialized_value()
课程中使用Variable
方法:
https://github.com/tensorflow/tensorflow/blob/r1.5/tensorflow/python/ops/variables.py#L533
来自doc字符串:
# Initialize 'v' with a random tensor.
v = tf.Variable(tf.truncated_normal([10, 40]))
# Use `initialized_value` to guarantee that `v` has been
# initialized before its value is used to initialize `w`.
# The random values are picked only once.
w = tf.Variable(v.initialized_value() * 2.0)