1、variable_scope
'''
variable_scope 主要是给variable_name加前缀,
也可以给op_name加前缀
'''
import tensorflow as tf
def f1():
# tf.variable_scope().reuse默认为False
# 当reuse==False
with tf.variable_scope('var'):
v = tf.get_variable('v',[1])
v2 = tf.get_variable('v',[1])
# 报错,var/v已经存在,v2不能再定义
return v,v2
def f2():
# 当reuse==True
with tf.variable_scope('var'):
v = tf.get_variable('v',initializer=tf.constant(2.0))
with tf.variable_scope('var',reuse=True):
v2 = tf.get_variable('v',initializer=tf.constant(3.0))
print(v.name) # var/v:0
print(v2.name) #var/v:0
#sess print的值是:v=2.0,v2=2.0
return v,v2
def f3():
with tf.variable_scope('var')as var_scope:
v = tf.get_variable('v',initializer=tf.constant(2.0))
with tf.variable_scope(var_scope):
v2 = tf.get_variable('w',initializer=tf.constant(3.0))
print(tf.get_variable_scope()) # 获得当前作用域
print(v.name) # var/v:0
print(v2.name) #var/w:0
#sess print的值是:v=2.0,v2=3.0
return v,v2
def f4():
# 如果在开启的一个变量作用域里使用之前预先定义的一个作用域,则会跳过当前变量的作用域,保持预先存在的作用域不变
with tf.variable_scope('var') as var_scope:
print(var_scope.name) # var
with tf.variable_scope('var2') as var2_scope:
print(var2_scope.name) # var2
with tf.variable_scope('var3') as var3_scope:
print(var3_scope.name) # var2/var3
with tf.variable_scope(var_scope) as var4_scope:
print(var4_scope.name) # var
with tf.variable_scope('var5') as var5_scope:
print(var5_scope.name) # var2/var3/var5
return 0
def f5():
# 变量作用域的初始化
with tf.variable_scope('var',initializer=tf.constant_initializer(0.4)) as var_scope:
v = tf.get_variable('v',[2]) # [0.4,0.4],被作用域初始化
v1 = tf.get_variable('w',[1],initializer=tf.constant_initializer(0.3)) # [0.3],重写初始化器的值
with tf.variable_scope('var2') as var2_scope:
v2 = tf.get_variable('u',[1]) # [0.4],继承父作用域的初始化器
with tf.variable_scope('var3',initializer=tf.constant_initializer(0.2)):
v3 = tf.get_variable('x',[1]) # [0.2],重写父作用域的初始化器的值
return v,v1,v2,v3
def f6():
# tf.Variable
with tf.variable_scope('var'):
a = tf.Variable(tf.zeros(2),name='v')
print(a.name) # var/v:0
return a
def f7():
# 对于op_name
with tf.variable_scope('op1'):
x = 1.0+tf.get_variable('v',[1])
print(x.name) # op1/add:0
print(x.op.name) # op1/add
2、name_scope
'''
tensorflow模型中常常有数以千万计的节点,在可视化时一般很难展示出来,
用name_scope为变量划分范围,name_scope给op_name加前缀,
name_scope不会影响用variable_scope()创建的变量,而会影响用Variable()创建的变量
'''
import tensorflow as tf
with tf.variable_scope('var'):
w = tf.Variable(tf.zeros([1]),name='c')
with tf.name_scope('layer1'):
v = tf.get_variable('v',[1],initializer = tf.constant_initializer(2.0))
b = tf.Variable(tf.zeros([1]),name='bias')
x = v*1.0+b+w
print(w.name) # var/c:0
print(v.name) # var/v:0
print(b.name) # var/layer1/bias:0
print(x.name) # var/layer1/add:0
print(x.op.name) # var/layer1/add