# 《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
tensorflow09 《TensorFlow实战Google深度学习框架》笔记-05-02变量管理(命名空间)code
最新推荐文章于 2025-07-26 10:48:19 发布