Tensorflow— name/variable_scope

代码:

import tensorflow as tf

# tf.name_scope 主要结合 tf.Variable() 来使用,方便参数命名管理。
# 创建一个命名空间
with tf.name_scope("conv1"):
    weights1 = tf.Variable([1.0,2.0], name='weights')
    bias1 = tf.Variable([0.1], name='bias')
# 创建另外一个命名空间来定义变量    
with tf.name_scope("conv2"):
    weights2 = tf.Variable([2.0,2.0], name='weights')
    bias2 = tf.Variable([0.2], name='bias')
    
# weights1 和 weights2 这两个引用名指向了不同的空间,不会冲突
print(weights1.name)
print(weights1)
print(weights2.name)
print(weights2)

# 执行完 with 里边的语句之后,这个 conv1/ 和 conv2/ 空间还是在内存中的
# 如果再次执行上面的代码,会再生成其他命名空间

运行结果:

conv1/weights:0
<tf.Variable 'conv1/weights:0' shape=(2,) dtype=float32_ref>
conv2/weights:0
<tf.Variable 'conv2/weights:0' shape=(2,) dtype=float32_ref>

代码:

# tf.variable_scope() 主要结合 tf.get_variable() 来使用,实现变量共享。

with tf.variable_scope('vs1'):
    weights1 = tf.get_variable('weights', shape=[2,3])
    bias1 = tf.Variable([0.52], name='bias')

# 变量必须已经定义过了,才能设置 reuse=True,否则会报错
with tf.variable_scope('vs1', reuse=True):
    weights2 = tf.get_variable('weights')
    bias2 = tf.Variable([0.52], name='bias')
    
# 可以看到这两个引用名称指向的是同一个内存对象
print(weights1.name)
print(weights2.name)
print("===" * 20)
print(bias1.name)
print(bias2.name)

运行结果:

vs1/weights:0
vs1/weights:0
============================================================
vs1/bias:0
vs1_1/bias:0

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值