How can I get the current value of a variable while ensuring that it has been initialized already? tf.Variable.initialized_value()
has a dependency on the initializer that causes the variable to be reset to its initial value every time it is accessed. To prevent the variable from being reset, I tried to use tf.cond()
with tf.is_variable_initialized()
as predicate. However, this does not work since the true-branch of the conditional requires the variable to be initialized, even though the false-branch is active:
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