tf.get_variable
此函数通过变量名称创建或获取一个变量。
和tf.variable最大区别在变量名称:
tf.get_variable | tf.variable |
---|---|
必填,若有同名参数,报错 | 可选,name=“v” |
如果需要通过get_variable获取已经创建的变量,则使用 tf.variable_scope生成上下文管理器
如下:
with tf.variable_scope("foo"):
v =tf.get_variable("v",[1],initializer=tf.constant_initializer(1.0))
with tf.variable_scope("foo",reuse=True):
v1 = tf.get_variable("v",[1])
print (v==v1)#输出True
reuse=True时,tf.variable_scope只能获取已经创建的变量,其中所有的tf.get_variable将直接获取已经创建的变量;reuse=None/False,tf.get_variable会创造新的变量
tf.variable_scope还可以嵌套:
with tf.variable_scope("root"):
print(tf.get_variable_scope().reuse) #输出False
with tf.get_variable_scope("foo",reuse=True):
print(tf.get_variable_scope().reuse) #输出True
with tf.get_variable_scope("bar"):
print(tf.get_variable_scope().reuse) #输出True
print(tf.get_variable_scope().reuse) #False
通过tf.variable_scope来管理变量的名称:
with tf.get_variable_scope("foo"):
with tf.get_variable_scope("bar"):
v1 = tf.get_variable("v",[1])
print(v1.name)#输出“foo/bar/v:0”