tf.get_variable与tf.Variable的以及tf.name_scope与tf.variable_scope的区别

# 下面这两个定义是等价的。

 v = tf .get_variable (”v”, shape=[l] , initializer=tf.constant initializer(l.0)) 
 v = tf.Variable(tf.constant(l.0, shape=[l)), name=”v” )  

先说参数怎么定义

tf.get_variable()必须指定name,shape,initializer方法。
tf.Variable()只指定参数tensor即可,可以是np.narray()等,一定要是实数。

关于变量管理

tf.variable_scope可以同时对tf.get_variable和tf.Variable进行命名管理。

with tf.variable_scope (” foo”, reuse=True) : 
        v1 = tf.get_variable (” v”,[1])  
with tf.variable_scope (” foo”, reuse=True) : 
        v2 = tf.Variable(” v”,[1]) 

以上代码均可以在变量‘v’前,添加‘fo’,变成‘foo/v:0’
v1 : ‘foo/v:0’
v2 : ‘foo/v:0’
tf.variable_scope可以同时对tf.get_variable和tf.Variable进行命名管理。
再说name_scope管理

with tf.name_scope (” foo”, reuse=True) : 
  v1 = tf.get_variable (” v”,[1])  
with tf.naem_scope (” foo”, reuse=True) : 
  v2 = tf.Variable(” v”,[1]) 

name_scope对tf.get_variable不影响
v1 : ‘v:0’
v2 : ‘foo/v:0’

tf.variable_name()有参数reuse可以共享参数

当 tf.variable_ scope 函数使用参数 reuse=True 生成上下文管理器时,这个上下文管理器内所 有的 tf.get_variable 函数会直接获取己经创建的变量。如果变量不存在,则 tf.get_variable 函数将报错:相反,如果 tf.variable_ scope 函数使用参数 reuse=None 或者 reuse=False 创建 上下文管理器, tf.get_variable 操作将创建新的变量。
如果同名的变量已经存在,则tf.get_ variable 函数将报错。 TensorFlow 中 tf.variable_scope 函数是可以嵌套的。下面的程序 说明了当 tf.variable_ scope 函数嵌套时, reuse 参数的取值是如何确定的。

参考:TensorFlow: 实战 Google 深度学习框架(第 2 版)

你可能感兴趣的:(tf.get_variable与tf.Variable的以及tf.name_scope与tf.variable_scope的区别)