Python 无法使用初始化的局部变量

Python 无法使用初始化的局部变量,python,tensorflow,Python,Tensorflow,我想在TensorFlow模型中使用局部变量,但我发现这样做很麻烦。我已将我的问题总结为以下示例: import tensorflow as tf with tf.device('/cpu:0'): v = tf.get_local_variable('myvar', [1, 1], initializer=tf.zeros_initializer()) with tf.control_dependencies([tf.variables_initializer([v])]):

我想在TensorFlow模型中使用局部变量,但我发现这样做很麻烦。我已将我的问题总结为以下示例:

import tensorflow as tf

with tf.device('/cpu:0'):
    v = tf.get_local_variable('myvar', [1, 1], initializer=tf.zeros_initializer())
    with tf.control_dependencies([tf.variables_initializer([v])]):
        v2 = tf.identity(v, name='myvar2')

with tf.Session() as sess:
    print(sess.run(v2))
我希望得到
[[0.]]
,但得到的却是错误:

FailedPreconditionError (see above for traceback): Attempting to use uninitialized value myvar
         [[Node: myvar/read = Identity[T=DT_FLOAT, _class=["loc:@myvar"], _device="/job:localhost/replica:0/task:0/cpu:0"](myvar)]]
那么我应该如何初始化和使用局部变量呢

我使用的是TensorFlow 1.0.0和Python 3.5

更新:

我注意到,亲自完成初始化任务确实有效:

那么,无论您如何设置依赖项,初始化器是否总是在会话结束时运行?还是我还遗漏了什么


注意:这个解决方案对我来说是不够的(至少是这样),因为我想在变量中执行切片赋值,而我不能对
.assign
的返回值执行切片赋值,它是对变量的引用,而不是变量本身。我已经看到使用
v_assigned
作为控件依赖项,然后分配给
v
似乎是可行的,但我不知道这是否可靠。

因此,显然问题在于我假设使用
tf.identity
会给我一个变量的引用,但会使用当前控件依赖项进行更新,但事实并非如此;它只是给了我一个旧(可能未初始化)值的引用。因此正确的方法是使用
tf.Variable
read\u value
方法,如中所述。因此正确的代码应该是:

import tensorflow as tf

with tf.device('/cpu:0'):
    v = tf.get_local_variable('myvar', [1, 1], initializer=tf.zeros_initializer())
    with tf.control_dependencies([tf.variables_initializer([v])]):
        v2 = tf.identity(v.read_value(), name='myvar2')

with tf.Session() as sess:
    print(sess.run(v2))
import tensorflow as tf

with tf.device('/cpu:0'):
    v = tf.get_local_variable('myvar', [1, 1], initializer=tf.zeros_initializer())
    with tf.control_dependencies([tf.variables_initializer([v])]):
        v2 = tf.identity(v.read_value(), name='myvar2')

with tf.Session() as sess:
    print(sess.run(v2))