首页 > 解决方案 > 如何用变量名更新 tf.variable_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) 的不同列表,但值始终相同。

标签: tensorflowscope

解决方案


您需要在图形部分运行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')

推荐阅读