tensorflow: 1.3.0
python: 3.6.1
def test0():
""" 重名不报错, Variable()本身自动创建别名 """
var3 = tf.Variable(name='var2', initial_value=[2], dtype=tf.float32)
var4 = tf.Variable(name='var2', initial_value=[2], dtype=tf.float32)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print(var3.name, sess.run(var3)) # var2:0 [ 2.]
print(var4.name, sess.run(var4)) # var2_1:0 [ 2.]
def test1():
""" 重名不报错, Variable()本身自动创建别名并受name_scope影响 """
with tf.name_scope('name_scope_x'):
var3 = tf.Variable(name='var2', initial_value=[2], dtype=tf.float32)
var4 = tf.Variable(name='var2', initial_value=[2], dtype=tf.float32)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print(var3.name, sess.run(var3)) # name_scope_x/var2:0 [ 2.]
print(var4.name, sess.run(var4)) # name_scope_x/var2_1:0 [ 2.]
def test2():
""" 重名会报错, get_variable()不会自动创建别名 """
var1 = tf.get_variable(name='var1', shape=[1], dtype=tf.float32)
var2 = tf.get_variable(name='var1', shape=[1], dtype=tf.float32)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print(var1.name, sess.run(var1))
print(var2.name, sess.run(var2))
def test3():
""" 重名会报错, get_variable不会自动创建别名且不受name_scope影响 """
with tf.name_scope('name_scope_1'):
var1 = tf.get_variable(name='var1', shape=[1], dtype=tf.float32)
print(var1.name) # var1:0
var2 = tf.get_variable(name='var1', shape=[1], dtype=tf.float32)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print(var1.name, sess.run(var1))
print(var2.name, sess.run(var2))
def test4():
""" 重名不报错,
get_variable()不受name_scope影响, 参见test3
Variable()受variable_scope影响, 但是会自动重命名防冲突, 参见test0,test1
"""
with tf.variable_scope('variable_scope_y') as scope:
var1 = tf.get_variable(name='var1', shape=[1], dtype=tf.float32)
scope.reuse_variables() # 设置共享变量
var1_reuse = tf.get_variable(name='var1') # 重名不报错
var2 = tf.Variable(initial_value=[2.], name='var2', dtype=tf.float32)
var2_reuse = tf.Variable(initial_value=[2.], name='var2', dtype=tf.float32)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print(var1.name, sess.run(var1)) # variable_scope_y/var1:0 [ 0.71645534]
print(var1_reuse.name, sess.run(var1_reuse))# variable_scope_y/var1:0 [ 0.71645534]
print(var2.name, sess.run(var2)) # variable_scope_y/var2:0 [ 2.]
print(var2_reuse.name, sess.run(var2_reuse))# variable_scope_y/var2_1:0 [ 2.]
def test5():
""" name_scope只能控制操作Ops的名字,而控制不了变量Variables的名字 """
with tf.variable_scope("foo"):
with tf.name_scope("bar"):
v = tf.get_variable("v", [1])
x = 1.0 + v
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print(v, sess.run(v)) # <tf.Variable 'foo/v:0' shape=(1,) dtype=float32_ref> [ 0.65264714]
print(x, sess.run(x)) # Tensor("foo/bar/add:0", shape=(1,), dtype=float32) [ 1.65264714]
参考: