tf.Variable()和tf.get_variable()都可以用来创建变量,但是前者会自动保证唯一性,而后者不能保证唯一性。
1 tf.Variable:
Variable(initial_value=None, trainable=True,
collections=None, validate_shape=True,
caching_device=None,name=None,
expected_shape=None, import_scope=None,
constraint=None)
新建一个变量,变量值是initial_value.
params:
initial_value:初始值
name:可选参数,变量的名字,会自动保证唯一性。
2 tf.get_variable():
get_variable(name, shape=None, dtype=None,
initializer=None, regularizer=None,
trainable=True, collections=None,
caching_device=None, partitioner=None,
validate_shape=True, use_resouce=None,
constraint=None)
获取具有这些参数的现有变量或创建一个新变量。如果该name的变量还未定义,则新创建一个;如果已经定义了,则直接获得该变量。
get_variable()可以用来创建共享变量。
下面用例子来说明二者的不同之处:
import tensorflow as tf
with tf.variable_scope('scope1'):
w1 = tf.Variable(1, name='w1')
w2 = tf.get_variable(name='w2', initializer=2.)
with tf.variable_scope('scope1', reuse=True):
w1_p = tf.Variable(1, name='w1')
w2_p = tf.get_variable(name='w2', initializer=3.)
print('w1', w1)
print('w1_p', w1_p)
print('w2', w2)
print('w2_p', w2_p)
print(w1 is w1_p, w2 is w2_p)
输出结果如下:
w1 <tf.Variable 'scope1/w1:0' shape=() dtype=int32_ref>
w1_p <tf.Variable 'scope1_1/w1:0' shape=() dtype=int32_ref>
w2 <tf.Variable 'scope1/w2:0' shape=() dtype=float32_ref>
w2_p <tf.Variable 'scope1/w2:0' shape=() dtype=float32_ref>
False True
可以看出,tf.Variable()会自动处理冲突问题,如代码中所示,他会将scope1改为scope1_1。
而tf.get_variable()会判断是否已经存在该name的变量,如果有,并且该变量空间的reuse=True,那么就可以直接共享之前的值;如果没有,则重新创建。注意,如果你没有将reuse设为True,则会提示冲突发生。
代码中最后一条语句判断上述变量是否相等,可以看出,通过get_variable()定义的变量是完全等价的,即使后一条get_variable将initializer设为3.,但是由于name=’w2’的变量已经存在,并且reuse=True,则直接引用之前定义的。这样就可以用get_variable()来定义共享变量。
你会发现,tf.get_variable()使用时,一般会和tf.variable_scope()配套使用,需要指定它的作用域空间,这样在引用的使用就可以通过设置指定的scope的reuse=True进行引用。下面讲解一下tf.variable_scope()和tf.name_scope()。
name_scope()是给op_name加前缀,指明op的作用域空间的,op是指操作。而variable_scope()是给get_variable()创建的变量的名字加前缀,表明作用域空间,也可以用于处理命名冲突。
with tf.name_scope('name_test'):
n1 = tf.constant(1, name='cs1')
n2 = tf.Variable(tf.zeros([1]), name='v1')
nv1 = tf.get_variable(name='nv1', initializer=1.0)
with tf.variable_scope('v_test'):
v_n1 = tf.constant(2, name='cs2')
v_n2 = tf.Variable(tf.zeros([1]), name='v2')
v1 = tf.get_variable(name='vv1', initializer=2.0)
print('n1', n1.name)
print('n2', n2.name)
print('nv1', nv1.name)
print('v_n1', v_n1.name)
print('v_n2', v_n2.name)
print('v1', v1.name)
输出结果如下:
n1 name_test/cs1:0
n2 name_test/v1:0
nv1 nv1:0
v_n1 v_test/cs2:0
v_n2 v_test/v2:0
v1 v_test/vv1:0
可以看出,variable_scope()不仅对get_variable()有效,对普通的op也有效,能给它们加上前缀,指明作用域空间;而name_scope()仅仅对普通的op有效,对get_variable()无效,不能给后者加上前缀,指明作用空间。