Variable
tensorflow中有两个关于variable的op,tf.Variable()与tf.get_variable()下面介绍这两个的区别
使用tf.Variable时,如果检测到命名冲突,系统会自己处理。使用tf.get_variable()时,系统不会处理冲突,而会报错
import tensorflow as tf w_1 = tf.Variable(3,name="w_1") w_2 = tf.Variable(1,name="w_1") print w_1.name print w_2.name #输出 #w_1:0 #w_1_1:0
import tensorflow as tf w_1 = tf.get_variable(name="w_1",initializer=1) w_2 = tf.get_variable(name="w_1",initializer=2) #错误信息 #ValueError: Variable w_1 already exists, disallowed. Did #you mean to set reuse=True in VarScope?
基于这两个函数的特性,当我们需要共享变量的时候,需要使用tf.get_variable()
。在其他情况下,这两个的用法是一样的
- tf.get_variable() 以及 tf.Variable() 是 TensorFlow 中创建变量的两种主要方式;
- 如果在 tf.name_scope() 环境下分别使用 tf.get_variable() 和 tf.Variable(),两者的主要区别在于
-
- tf.get_variable() 创建的变量名不受 name_scope 的影响;
- tf.get_variable() 创建的变量,name 属性值不可以相同;tf.Variable() 创建变量时,name 属性值允许重复(底层实现时,会自动引入别名机制
import tensorflow as tf with tf.variable_scope("scope1"): w1 = tf.get_variable("w1", shape=[]) w2 = tf.Variable(0.0, name="w2") with tf.variable_scope("scope1", reuse=True): w1_p = tf.get_variable("w1", shape=[]) w2_p = tf.Variable(1.0, name="w2") assert w1 == w1_p assert w2 != w2_pget_variable() 函数的行为依赖于 reuse 的状态:
-
case1:reuse 设置为 False,创建并返回新变量:
with tf.variable_scope('foo'): v = tf.get_variable('v', [1]) assert v.name == 'foo/v:0
-
case2:reuse 设置为 True,将会按照给定的名字在以存的变量中搜寻:
with tf.variable_scope('foo'): v = tf.get_variable('v', [1]) with tf.variable_scope('foo', reuse=True): v1 = tf.get_variable('v') assert v1 == v
tf.Variable()
每次都在创建新对象,所有
reuse=True
和它并没有什么关系。对于
get_variable()
,来说,如果已经创建的变量对象,就把那个对象返回,如果没有创建变量对象的话,就创建一个新的。
variable_scope()
一个双层嵌套名称空间:with tf.variable_scope('foo'): with tf.variable_scope('bar'): v = tf.get_variable('v', [1]) assert v.name == 'foo/bar/v:0'
with tf.name_scope('foo'): with tf.variable_scope('bar'): v = tf.get_variable('v', [1]) assert v.name == 'bar/v:0'