变量范围和get_varible

时间:2017-12-12 09:57:36

标签: tensorflow

为什么我不能得到100的结果,而是一个随机数?代码如下:

def func1():
    with tf.variable_scope("var_scope"):
        v1 = tf.get_variable('var1', shape=[])
        v1 = tf.zeros([1])
        v1 = v1 + 100

def func2():
    with tf.variable_scope("var_scope", reuse=True):
        v2 = tf.get_variable('var1')

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

func1()
func2()

1 个答案:

答案 0 :(得分:1)

写作时

v1 = tf.get_variable('var1', shape=[])

...在func1中,此变量随机初始化。 func1中的后续操作不会更改此节点,而是定义 new 节点。请记住,计算图中的python变量和tensorflow节点之间存在差异。

将代码更改为

v1 = tf.get_variable('var1', shape=[], initializer=tf.constant_initializer(0))

...看到差异。

相关问题