Tensorflow入门(五)——变量管理

tf.get_variable

此函数通过变量名称创建或获取一个变量。
和tf.variable最大区别在变量名称:

tf.get_variabletf.variable
必填,若有同名参数,报错可选,name=“v”

如果需要通过get_variable获取已经创建的变量,则使用 tf.variable_scope生成上下文管理器
如下:

with tf.variable_scope("foo"):
     v =tf.get_variable("v",[1],initializer=tf.constant_initializer(1.0))
with tf.variable_scope("foo",reuse=True):
     v1 = tf.get_variable("v",[1])
	 print (v==v1)#输出True

reuse=True时,tf.variable_scope只能获取已经创建的变量,其中所有的tf.get_variable将直接获取已经创建的变量;reuse=None/False,tf.get_variable会创造新的变量
tf.variable_scope还可以嵌套:

 with tf.variable_scope("root"):
     print(tf.get_variable_scope().reuse)	#输出False
     with tf.get_variable_scope("foo",reuse=True):
         print(tf.get_variable_scope().reuse)	#输出True
         with tf.get_variable_scope("bar"):
             print(tf.get_variable_scope().reuse)	#输出True
     print(tf.get_variable_scope().reuse)	#False
     

通过tf.variable_scope来管理变量的名称:

with tf.get_variable_scope("foo"):
    with tf.get_variable_scope("bar"):
        v1 = tf.get_variable("v",[1])
        print(v1.name)#输出“foo/bar/v:0”
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值