0

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
danijar
  • 32,406
  • 45
  • 166
  • 297
  • I guess you can find a couple of good answers at the following post: http://stackoverflow.com/questions/35164529/in-tensorflow-is-there-any-way-to-just-initialize-uninitialised-variables – Ali Mar 07 '17 at 19:57

1 Answers1

0

Use the initialized_value() method on the Variable class: https://github.com/tensorflow/tensorflow/blob/r1.5/tensorflow/python/ops/variables.py#L533

From the doc string:

# 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)
Dr K
  • 416
  • 2
  • 5