tensorflow09 《TensorFlow实战Google深度学习框架》笔记-05-02变量管理(命名空间)code

# 《TensorFlow实战Google深度学习框架》05 minist数字识别问题
# win10 Tensorflow1.0.1 python3.5.3
# CUDA v8.0 cudnn-8.0-windows10-x64-v5.1
# filename:ts05.08.py # 变量管理(命名空间)

import tensorflow as tf

# 1. 在上下文管理器“foo”中创建变量“v”。
with tf.variable_scope("foo"):
    v = tf.get_variable("v", [1], initializer=tf.constant_initializer(1.0))
'''
with tf.variable_scope("foo"):
    v = tf.get_variable("v", [1])
# ValueError: Variable foo/v already exists, disallowed. Did you mean to set reuse=True in VarScope? Originally defined at:
'''

with tf.variable_scope("foo", reuse=True):
    v1 = tf.get_variable("v", [1])
print(v == v1) # True
'''
with tf.variable_scope("bar", reuse=True):
    v = tf.get_variable("v", [1])
# ValueError: Variable bar/v does not exist, or was not created with tf.get_variable(). Did you mean to set reuse=None in VarScope?
'''

# 2. 嵌套上下文管理器中的reuse参数的使用
with tf.variable_scope("root"):
    print(tf.get_variable_scope().reuse) # False
    with tf.variable_scope("foo", reuse=True):
        print(tf.get_variable_scope().reuse) #True
        with tf.variable_scope("bar"):
            print(tf.get_variable_scope().reuse) # True
    print(tf.get_variable_scope().reuse) # False

# 3. 通过variable_scope来管理变量
v1 = tf.get_variable("v", [1])
print(v1.name) # v:0

with tf.variable_scope("foo", reuse=True):
    v2 = tf.get_variable("v", [1])
print(v2.name) # foo/v:0

with tf.variable_scope("foo"):
    with tf.variable_scope("bar"):
        v3 = tf.get_variable("v", [1])
        print(v3.name) # foo/bar/v:0

v4 = tf.get_variable("v1", [1])
print(v4.name) # v1:0

# 4. 我们可以通过变量的名称来获取变量
with tf.variable_scope("",reuse=True):
    v5 = tf.get_variable("foo/bar/v", [1])
    print(v5 == v3) # True
    v6 = tf.get_variable("v1", [1])
    print(v6 == v4) # True
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值