name_scope与variable_scope
import tensorflow as tf
with tf.name_scope("a_name_scope"): 无reuse
initializer = tf.constant_initializer(value=1)
var1 = tf.get_variable(name='var1', shape=[1], dtype=tf.float32, initializer=initializer)
var2 = tf.Variable(name='var2', initial_value=[2], dtype=tf.float32)
var21 = tf.Variable(name='var2', initial_value=[2.1], dtype=tf.float32)
var22 = tf.Variable(name='var2', initial_value=[2.2], dtype=tf.float32)
with tf.Session() as sess:
sess.run(tf.initialize_all_variables())
print(var1.name) # var1:0 get_variable无前缀
print(sess.run(var1)) # [ 1.]
#-----------------------------------------------------------------------------------------------
print(var2.name) # a_name_scope/var2:0 Variable 有前缀
print(sess.run(var2)) # [ 2.]
print(var21.name) # a_name_scope/var2_1:0 且命名时同名的实际不同命 name_1/2/3...
print(sess.run(var21)) # [ 2.0999999]
print(var22.name) # a_name_scope/var2_2:0
print(sess.run(var22)) # [ 2.20000005]
tf.Variable() 每次都会产生新的变量,
tf.get_variable必须命名 且reuse=False时都不可重复声明
reuse=True时tf.get_variable只能取已声明的变量 不然报错
reuse=FALSE时tf.get_variable只能创未声明的变量 不然报错
variable_scope在嵌套时reuse不指定则同外层
with tf.variable_scope("a_variable_scope",’’’reuse=True’’’) as scope:
initializer = tf.constant_initializer(value=3)
var3 = tf.get_variable(name='var3', shape=[1], dtype=tf.float32, initializer=initializer)
scope.reuse_variables() ----------------------------------------------------------- !!!
var3_reuse = tf.get_variable(name='var3',)
var4 = tf.Variable(name='var4', initial_value=[4], dtype=tf.float32)
var4_reuse = tf.Variable(name='var4', initial_value=[4], dtype=tf.float32)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print(var3.name) # a_variable_scope/var3:0 get_variable有前缀
print(sess.run(var3)) # [ 3.]
print(var3_reuse.name) # a_variable_scope/var3:0 只在reuse==True时,重复利用变量(搭配variable_scope)
print(sess.run(var3_reuse)) # [ 3.] 甚至获取其他空间变量
----------------------------------------------------------------------------------------------
print(var4.name) # a_variable_scope/var4:0 Variable 有前缀
print(sess.run(var4)) # [ 4.]
print(var4_reuse.name) # a_variable_scope/var4_1:0
print(sess.run(var4_reuse)) # [ 4.]
参考:
http://blog.csdn.net/marsjhao/article/details/72829806