[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

额外说一下,reuse有三个值:

  • None (默认)
    继承上面的设置,如果没有就是AUTO_REUSE
  • AUTO_REUSE
    不用复用,但是如果没有值会自动创建
  • True
    会复用,但是在调用tf.get_variable时,如果没有会抛错
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值