一 实例描述
variable_scope还可以使用 with tf.variable_scope("name") as xxxscope的方式定义作用域,当使用这种方式时,所定义的作用域变量xxxscope将不再受外围scope所限制。
二 代码
import tensorflow as tf
tf.reset_default_graph()
with tf.variable_scope("scope1") as sp:
var1 = tf.get_variable("v", [1])
print("sp:",sp.name) #sp: scope1
print("var1:",var1.name) #var1: scope1/v:0
with tf.variable_scope("scope2"):
var2 = tf.get_variable("v", [1])
with tf.variable_scope(sp) as sp1: #将sp放在作用域scope2中,并as成sp1,使得v3不受外层scope限制
var3 = tf.get_variable("v3", [1])
with tf.variable_scope("") : #让v4多出一个空层
var4 = tf.get_variable("v4", [1])
print("sp1:",sp1.name) #sp1: scope1 sp1在scope2下,但是输出任是scope1,没有改变
print("var2:",var2.name) #var2: scope2/v:0
print("var3:",var3.name) #var3: scope1/v3:0 表明var3在scope1下,再次说明sp没有受到外层的限制。
print("var4:",var4.name) #var4: scope1//v4:0 v4多出一个空层
with tf.variable_scope("scope"):
with tf.name_scope("bar"):
v = tf.get_variable("v", [1])
x = 1.0 + v
with tf.name_scope(""): #空字符将作用域返回到顶层
y = 1.0 + v
print("v:",v.name) #v: scope/v:0 变量的命名只受到variable_scope限制,不受name_scope限制
print("x.op:",x.op.name) #x.op: scope/bar/add 操作符不仅受到name_scope作用域限制,同时也受variable_scope作用域限制。
print("y.op:",y.op.name) #y.op: add 在空字符作用域下,被返回到顶层
三 运行结果
sp: scope1
var1: scope1/v:0
sp1: scope1
var2: scope2/v:0
var3: scope1/v3:0
var4: scope1//v4:0
v: scope/v:0
x.op: scope/bar/add
y.op: add