0
点赞
收藏
分享

微信扫一扫

[tensorflow] tf.name_scope和tf.variable_scope

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。

运行结果

可以看到

  1. 通过tf.Variable得到的变量是带了name scope的,但是通过tf.get_variable是没有的
  2. 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

  1. tf.Variable可以重复执行,如v2v4,对于已经存在的,在命令上以下划线+1区别,如scope1/var2:0scope1/var2_1:0

  2. 所有的运算,其实都是有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)

运行结果

可以看到

  1. 无论tf.Variable还是tf.get_variable得到的variable都是带scope的
  2. 如果想通过tf.get_variable获取到已经存在的,而不是再新建一个,需要在scope里带一个参数reuse=True
举报

相关推荐

0 条评论