变量初始化有下边两种形式:
1.
tf.name_scope('a_name_scope'):
initializer = tf.constant_initializer(value=1)
var1 = tf.get_variable(name='var1', shape=[1], dtype=tf.float32, initializer=initializer)
2.
tf.name_scope('a_variable_scope'):
var2 = tf.Variable(name='var2', initial_value=[2], dtype=tf.float32)
var3 = tf.Variable(name='var2', initial_value=[2.1], dtype=tf.float32)
var4 = tf.Variable(name='var2', initial_value=[2.2], dtype=tf.float32)
结论:
tf.name_scope('a_name_scope')对第一种变量初始化无效,即无法为变量var1命名为a_name_scope;
对第二种有效,但是'var2'这个名字重复定义,结果就是var2的名字是a_name_scope/var2,var3的名字是a_name_scope/var2_1,var3的名字是a_name_scope/var2_2.
#########################################################################################
tf.variable_scope('a_variable_scope'):
initializer = tf.constant_initializer(value=3)
var3 = tf.get_variable(name='var3', shape=[1], dtype=tf.float32, initializer=initializer)
tf.variable_scope('a_variable_scope'):
var4 = tf.Variable(name='var4', initial_value=[4], dtype=tf.float32)
var5 = tf.Variable(name='var4', initial_value=[4], dtype=tf.float32)
结论:
tf.variable_scope('a_variable_scope')对以上两种变量初始化都有效.var3的名字是a_variable_scope/var3,var4的名字是a_variable_scope/var4,var5的名字是a_variable_scope/var4_1.
#########################################################################################
上述变量名nam='var4'和name='var2'都无法重复利用(因为var5的名字是a_variable_scope/var4_1,不是a_variable_scope/var4),若重复利用变量,可以使用下边语句形式:
tf.variable_scope('a_variable_scope'):
initializer = tf.constant_initializer(value=3)
var3 = tf.get_variable(name='var3', shape=[1], dtype=tf.float32, initializer=initializer)
scope.reuse_variables() #告诉编译器要重新利用这个名字,而不是错误语句
var3_reuse = tf.get_variable(name='var3') #不必重新定义get_variable的其他参数了
结论:var3的名字是a_variable_scope/var3,var3_reuse的名字也是a_variable_scope/var3,其实是一个变量一个空间,不是两个,值都为3.
############################共享变量###########################################
tf.variable_scope(name)的参数name给不同的名字,可以产生不同的作用域,不同name就是不同作用域,不同作用域下同样的变量名不会冲突报错,但是这不是共享同一个变量(reuse_variable),是不同的变量.
如果想共享变量,可以采用以下形式:
with tf_variable_scope('rnn') as scope:
train_rnn2 = RNN(training_config)
scope.reuse_variable()
test_rnn2 = RNN(testing_cofig)
结论:train_rnn2和test_rnn2共享RNN内部参数变量。
比如:
training_config()函数定义初始化的参数n_steps = 20,testing_config()函数定义初始化的参数是n_steps=1,当training和testing时,RNN内部结构有所变化(function 的 steps不一致),但是都要使用同样的已经训练好的RNN内部参数,即training和testing过程使用共享RNN内部function参数变量。