如何使用变量名称更新tf.variable_scope中的变量?

时间:2019-04-16 07:07:50

标签: tensorflow scope

我想在tf.variable_scope中修改有关变量'weight1'的值。

我尝试通过其他功能修改值,但是跟着我行不通。

def inference(q, reuse=False):
    with tf.variable_scope('layer1', reuse = reuse):
        x = tf.get_variable('weight1', [1, 3], initializer = tf.truncated_normal_initializer(stddev = 0.1))
        y = tf.get_variable('weight2', [3, 1], initializer = tf.constant_initializer([[1],[2],[3]]))
    return tf.matmul(x, y)



def update_process(reuse=True):
    with tf.variable_scope('layer1', reuse = reuse):
        x = tf.get_variable('weight1',[1, 3])
        update=tf.assign(x, x-1)

        with tf.Session() as sess:
            sess.run(init)
            print(sess.run(x))

init = tf.global_variables_initializer()    

z = inference(1)            
with tf.Session() as sess:
    sess.run(init)
    for i in range(5):
        update_process(reuse = True)
        print(sess.run(z))
        print('\n')

我希望此代码输出有关sess.run(z)的不同列表,但值始终相同。

1 个答案:

答案 0 :(得分:0)

您需要在图形的sess.run(update)部分运行的同一会话中,在update_process中运行inference

import tensorflow as tf

def inference(q, reuse=False):
    with tf.variable_scope('layer1', reuse = reuse):
        x = tf.get_variable('weight1', [1, 3], initializer = tf.truncated_normal_initializer(stddev = 0.1))
        y = tf.get_variable('weight2', [3, 1], initializer = tf.constant_initializer([[1],[2],[3]]))
    return tf.matmul(x, y)



def update_process(reuse=True):
    with tf.variable_scope('layer1', reuse = reuse):
        x = tf.get_variable('weight1',[1, 3])
        update=tf.assign(x, x-1)
        print(sess.run(update))


z = inference(1)            
init = tf.global_variables_initializer()    
with tf.Session() as sess:
    sess.run(init)
    for i in range(5):
        update_process(reuse = True)
        print(sess.run(z))
        print('\n')