tf.name_scope(), tf.variable_scope(), tf.Variable(), tf.get_variable()

这四个函数是互相联系的。下面翻译一下stackoverflow上的高票答案
what’s the difference of name scope and a variable scope in tensorflow?

翻译:
在讲name scope和variable scope之前,我们先简单介绍一下变量共享机制,这个机制使得tensorflow使得graph的其他部分也能调用之前定义过的变量。

tf.get_variable()方法可以用来创建新的变量或者用来检索之前已经定义过的变量。而tf.Variable是会一直创建新的变量,如果你命名重复,tf会自动给变量加一个后缀。

使用tf.variable_scope使得变量检索变得更简单。
简单来说
tf.name_scope()是给operator以及tf.Variable创建的variable创建namespace的
tf.variable_scope()是给variable和operator创建namespace的
也就是说,tf.get_variable()创建的变量是不受name_scope影响的
举个例子

with tf.name_scope("my_scope"):
    v1 = tf.get_variable("var1", [1], dtype=tf.float32)
    v2 = tf.Variable(1, name="var2", dtype=tf.float32)
    a = tf.add(v1, v2)

print(v1.name)  # var1:0 ,namescope被忽略了
print(v2.name)  # my_scope/var2:0
print(a.name)   # my_scope/Add:0
with tf.name_scope("foo"):
    with tf.variable_scope("var_scope"):
        v = tf.get_variable("var", [1])
with tf.name_scope("bar"):
    with tf.variable_scope("var_scope", reuse=True):
        v1 = tf.get_variable("var", [1])
print(v.name)   # var_scope/var:0
print(v1.name)  # var_scope/var:0

这使得我们可以在不同的name scope下共享变量.
这对大型网络在tensorboard中可视化非常有用,这个 教程 还可以

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值