https://www.cnblogs.com/MY0213/p/9270864.html
https://blog.youkuaiyun.com/brucewong0516/article/details/78788772
1、tf.variable与tf.get_variable
tensorflow提供了通过变量名称来创建或者获取一个变量的机制,通过变量名获取变量的机制主要是通过tf.get_variable和tf.variable_scope实现的。当然,变量也可以通过tf.Varivale来创建。当tf.get_variable用于变量创建时,和tf.Variable的功能基本等价。
#以下两个定义是等价的
v = tf.get_variable('v', shape=[1], initializer=tf.constant_initializer(1.0))
v = tf.Variable(tf.constant(1.0, shape=[1], name='v')
tf.get_varialbe和tf.Variable最大的区别在于:tf.Variable的变量名是一个可选项,通过name=’v’的形式给出。但是tf.get_variable必须指定变量名。
2、tf.get_variable与tf.variable_scope
TensorFlow中通过变量名获取变量的机制主要是通过tf.get_variable和tf.variable_scope实现的。关键是reuse问题,这里只要记住:当reuse为False或者None时(这也是默认值),同一个tf.variable_scope下面的变量名不能相同;当reuse为True时,tf.variable_scope只能获取已经创建过的变量。
示例代码:
#reuse=False时会报错的情况:
with tf.variable_scope('foo'):
v = tf.get_variable('v',[1],initializer=tf.constant_initializer(1.0))
with tf.variable_scope('foo'):
v1 = tf.get_variable('v',[1])
在这种情况下会报错:Variable foo/v already exists, disallowed.Did you mean to set reuse=True in Varscope?
其原因就是在命名空间foo中创建了相同的变量。如果要在foo下创建一个变量v1,其name=‘v’,只需要将reuse设置为Ture就ok了。将上面第二部分代码修改为:
with tf.variable_scope('foo', reuse=True):
v1 = tf.get_variable('v',[1])
print(v1.name) #结果为foo/v
tf.variable_scope函数生成的上下文管理器也会创建一个TensorFlow中的命名空间,在这个命名空间内创建的变量名称都会带上这个空间名作为前缀,因此tf.variable_scope函数可以管理变量命名空间。
示例代码:
import tensorflow as tf
with tf.variable_scope("bar"):
v0= tf.get_variable('v',[1],initializer = tf.constant_initializer(1.0))
with tf.variable_scope("bar",reuse =True):
v2= tf.get_variable('v',[1])
print(v2.name) #输出带有空间名:bar\v:0