name_scope
if __name__ == '__main__':
with tf.name_scope("scope1"):
v1 = tf.get_variable("var1", [1,2], dtype=tf.float32)
v2 = tf.Variable(1, name="var2", dtype=tf.float32)
v3 = tf.get_variable("var2", [1], dtype=tf.float32)
v4 = tf.Variable(1, name="var2", dtype=tf.float32)
a = tf.add(v1, v2)
print(v1)
print(v2)
print(v3)
print(v4)
print(a)
get_variable如果找不到,则重新创建一个。 第二个参数是shape。
可以看到
- 通过tf.Variable得到的变量是带了name scope的,但是通过tf.get_variable是没有的
- tf.get_variable获取的变量,如果已经存在,比如将v3改一下
v3 = tf.get_variable("var1", [1], dtype=tf.float32)
那么将出现异常
ValueError: Variable var1 already exists, disallowed. Did you mean to set reuse=True or reuse=tf.AUTO_REUSE in VarScope
-
tf.Variable可以重复执行,如
v2
和v4
,对于已经存在的,在命令上以下划线+1区别,如scope1/var2:0
和scope1/var2_1:0
-
所有的运算,其实都是有variable记录,所以a也是一个variable
variable_scope
with tf.variable_scope("scope1"):
v1 = tf.get_variable("var1", [1,2], dtype=tf.float32)
v2 = tf.Variable(1, name="var2", dtype=tf.float32)
v3 = tf.get_variable("scope1/var2", [1,2], dtype=tf.float32)
v4 = tf.Variable(1, name="var2", dtype=tf.float32)
a = tf.add(v1, v2)
print(v1)
print(v2)
print(v3)
print(v4)
print(a)
可以看到
- 无论tf.Variable还是tf.get_variable得到的variable都是带scope的
- 如果想通过tf.get_variable获取到已经存在的,而不是再新建一个,需要在scope里带一个参数reuse=True
额外说一下,reuse有三个值:
- None (默认)
继承上面的设置,如果没有就是AUTO_REUSE- AUTO_REUSE
不用复用,但是如果没有值会自动创建- True
会复用,但是在调用tf.get_variable时,如果没有会抛错