Tensorflow 变量

name_scopevariable_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=Truetf.get_variable只能取已声明的变量  不然报错

reuse=FALSEtf.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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
>