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


版权声明:本文为wangsiji_buaa原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。