tf.get_variable创建变量的时候必须提供name属性。如果再次运行该代码,报错:
ValueError: Variable gv already exists, disallowed. Did you mean to set reuse=True in VarScope?
可见,tf.get_variable用来实现变量共享。tf.get_variable创建的变量存在命名冲突的问题。而tf.Variable不存在命名冲突的问题,如果tf.Variable创建的变量name相同,就会创建一个新的变量,在name属性(或者name_scope)后加上后缀_1等。例如:
import tensorflow as tf
with tf.variable_scope('v_scope') as scope1:
Weights1 = tf.get_variable('Weights', shape=[2,3])
bias1 = tf.Variable([0.52], name='bias')
# 下面来共享上面已经定义好的变量
# note: 在下面的 scope 中的get_variable()变量必须已经定义过了,才能设置 reuse=True,否则会报错
with tf.variable_scope('v_scope', reuse=True) as scope2:
Weights2 = tf.get_variable('Weights')
bias2 = tf.Variable([0.52], name='bias')
bias3= tf.Variable([0.52], name='bias')
print(Weights1.name)
print(Weights2.name)
print(bias1.name)
print(bias2.name)
print(bias3.name)
输出:
v_scope/Weights:0
v_scope/Weights:0
v_scope/bias:0
v_scope_1/bias:0
v_scope_1/bias_1:0
tf.variable_scope包含tf.name_scope的作用,而且可以用来实现变量共享.
with tf.variable_scope('vs1', reuse=True) as vs:
tf.variable_scope中设置了reuse=True,则其中tf.get_variable()的变量必须是已经在vs1中通过tf.get_variable()方法声明的变量,否则报错:
ValueError: Variable vs1/var3 does not exist, or was not created with tf.get_variable().
而tf.Variable()方法不受reuse=True的影响。
tf.name_scope()对tf.get_variable()方法没有作用,起不到命名空间的作用。例如:
import tensorflow as tf
with tf.name_scope('nc1') as vs:
a = tf.get_variable('var1', shape=[2,4], dtype=tf.float32)
print(a.name)
输出:var1:0