import tensorflow as tf
with tf.variable_scope("scope1") as sp:
var1 = tf.get_variable("v1", [1])
print("sp:", sp.name)
print("var1:", var1.name)
with tf.variable_scope("scope2"):
var2 = tf.get_variable("v2", [1])
with tf.variable_scope(sp) as sp1: # 使用as xxx后变量不受作用域限制
var3 = tf.get_variable("v3", [1])
with tf.variable_scope(""):
var4 = tf.get_variable("v4", [1])
print("sp1:", sp1.name)
print("var2:", var2.name)
print("var3:", var3.name)
print("var4:", var4.name)
# sp: scope1
# var1: scope1/v1:0
# sp1: scope1
# var2: scope2/v2:0
# var3: scope1/v3:0
# var4: scope1//v4:0
with tf.variable_scope("scope3"):
with tf.name_scope("bar"):
v5 = tf.get_variable("v5", [1]) # name_scope只能限制op,不能限制变量的命名
x = 1.0 + v5
with tf.name_scope(""):
y = 1.0 + v5
print("v4:", v5.name)
print("x.op:", x.op.name)
print("y.op:", y.op.name)
# v5: scope3/v5:0
# x.op: scope3/bar/add
# y.op: add # y变成了顶层 var4多了一个空层
variable_scope作用域
最新推荐文章于 2020-10-03 12:34:31 发布