以下内容从《TensorFlow 实战Google深度学习框架》整理得出
tf.Variable
函数用来创建一个变量,但是 TensorFlow 中海提供了 tf.get_variable
函数来创建或者获取变量。当 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.Variable
和 tf.get_varialbe
函数创建变量的过程基本上是一样的。tf.get_variable
函数调用时提供的维度(shape)信息以及初始化方法(initializer)的参数和tf.Variable
函数调用时提供的初始化过程中的参数也类似。
tf.get_variable
函数与 tf.Variable
函数最大的区别在于指定变量名称的参数。对于 tf.Variable
函数,变量名称是一个可选的参数,通过 name = “v” 的形式给出。但是对于 tf.get_variable
函数,变量名称是一个必填的参数。tf.get_variable
函数会根据这个名字去创建或者获取变量。
如果需要通过 tf.get_variable
获取一个已经创建的变量,需要通过 tf.variable_scope
函数来生成一个上下文管理器,并明确指定在这个上下文管理器中,tf.get_variable
将直接获取已经生成的变量。比如下列代码:
# 在名字 foo 的命名空间内创建名字为 v 的变量。
with tf.variable_scope("foo"):
v = tf.get_variable("v", [1],
initializer = tf.constant_initializer(1.0))
# 因为在命名空间 foo 中已经存在名字为 v 的变量,所有下面的代码将会报错;
# Variable foo/v already exists, disallowed. Did you mean to set reuse = True in VarScope?
# 在生成上下文管理器时,将参数 reuse 设置为 True。这样 tf.get_variable 函数将直接获取已经声明的变量。
with tf.variable_scope("foo", reuse = True):
v1 = tf.get_variable("v", [1])
print v == v1 # 输出为 True,代表 v,v1代表的是相同的 TensorFlow 中的变量。
# 将参数 reuse 设置为 True 时,tf.variable_scope 将只能获取已经创建过的变量。因为在命名空间 bar 中还没有创建变量 v,所以下面的代码将会报错:]
# Variable bar/v does not exist, disallowed. Did you mean to set reuse = None in VarScope?
wiht tf.variable_scope("bar", reuse = True):
v = tf.get_varialbe("v", [1])
但是,TensorFlow 中 tf.variable_scope
函数也是可以嵌套的。比如下面的程序,reuse
参数的取值是如何确定的呢?
with tf.variable_scope("root"):
# 可以通过 tf.get_variable_scope().reuse 函数来获取当前上下文管理器中 reuse 参数的取值。
print tf.get_variable_scope().reuse # 输出 False,即最外层 reuse 是 False。
with tf.variable_scope("foo", reuse = True): # 新建一个嵌套的上下文管理器,并制定 reuse 为 True。
print tf.get_variable_scope().reuse # 输出 True
with tf.variable_scope("bar"): # 新建一个嵌套的上下文管理器但不指定 reuse,这时 reuse的取值会和外面一层保持一致。
print tf.get_varialbe_scope().reuse # 输出 True
print tf.get_variable_scope().reuse # 输出 False。退出 reuse 设置为 True 的上下文之后 reuse 的值又回到了 False。
如果觉得内容有用,帮助多多分享哦 :)
长按或者扫描如下二维码,关注 “CoderPai” 微信号(coderpai)。添加底部的 coderpai 小助手,添加小助手时,请备注 “算法” 二字,小助手会拉你进算法群。如果你想进入 AI 实战群,那么请备注 “AI”,小助手会拉你进AI实战群。