翻译自:https://stackoverflow.com/questions/35919020/whats-the-difference-of-name-scope-and-a-variable-scope-in-tensorflow

问题:下面这几个函数的区别是什么?

tf.variable_op_scope(values, name, default_name, initializer=None)
Returns a context manager for defining an op
that creates variables. This context manager validates that the given values
are from the same graph, ensures that that graph is the default graph, and
pushes a name scope and a variable scope.

tf.op_scope(values, name, default_name=None)
Returns a context manager for use when
defining a Python op. This context manager validates that the given values are
from the same graph, ensures that that graph is the default graph, and pushes a
name scope.

tf.name_scope(name)
Wrapper for Graph.name_scope() using the
default graph. See Graph.name_scope() for more details.

tf.variable_scope(name_or_scope,
reuse=None, initializer=None)
Returns a context for variable scope. Variable
scope allows to create new variables and to share already created ones while
providing checks to not create or share by accident. For details, see the
Variable Scope How To, here we present only a few basic examples.

回答1:

首先简单介绍一下变量共享(variable sharing)。这是Tensorflow中的一种机制,它允许在代码的不同位置可以访问到共享变量(在不需要传递变量引用的情况下)。tf.get_variable方法可以将变量的名字作为参数,以创建具有该名称的新变量或者如果已经存在这个变量了,就取回这个变量。这与 tf.Variable是不同的。每次调用 tf.Variable都会创建一个新的变量(如果具有此名称的变量已经存在,则可能向变量名添加后缀)。针对共享变量机制,引进了scope (variable scope) 。

结果,我们有2中不同的scopes类型:

这两个scopes在所有的操作(operation)和使用tf.Variable创建的变量上都有相同的作用。

然而,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
print(v2.name) # my_scope/var2:0
print(a.name) # my_scope/Add:0

在一个scope中使用tf.get_variable来使得变量可以被访问唯一方法就是使用一个variable scope,例子如下:

with tf.variable_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) # my_scope/var1:0
print(v2.name) # my_scope/var2:0
print(a.name) # my_scope/Add:0

这可以使得我们在程序的不同地方可以很容易的共享变量,甚至在不同的name scope中:

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])
assert v1 == v
print(v.name) # var_scope/var:0
print(v1.name) # var_scope/var:0

更新:

Tensorflow版本r0.11之后,op_scope 和 variable_op_scope都被弃用了,替代的是op_scope 和 variable_op_scope

回答2:

举了一个例子,并将其可视化。

import tensorflow as tf
def scoping(fn, scope1, scope2, vals):
with fn(scope1):
a = tf.Variable(vals[0], name='a')
b = tf.get_variable('b', initializer=vals[1])
c = tf.constant(vals[2], name='c')
with fn(scope2):
d = tf.add(a * b, c, name='res') print '\n '.join([scope1, a.name, b.name, c.name, d.name]), '\n'
return d d1 = scoping(tf.variable_scope, 'scope_vars', 'res', [1, 2, 3])
d2 = scoping(tf.name_scope, 'scope_name', 'res', [1, 2, 3]) with tf.Session() as sess:
writer = tf.summary.FileWriter('logs', sess.graph)
sess.run(tf.global_variables_initializer())
print sess.run([d1, d2])
writer.close()

输出结果如下:

scope_vars
scope_vars/a:0
scope_vars/b:0
scope_vars/c:0
scope_vars/res/res:0 scope_name
scope_name/a:0
b:0
scope_name/c:0
scope_name/res/res:0

在TensorBoard中可视化如下:

从上面的可以看出来,tf.variable_scope()为所有变量(不管你是怎么创建的)、操作(ops)、常量(constant)添加一个前缀,而tf.name_scope()会忽视使用tf.get_variable()创建的变量,因为它假设你知道你使用的变量位于哪个scope中。

Sharing variables文档中告诉你:

tf.variable_scope(): Manages namespaces for names passed to tf.get_variable().

更详细的可以查看官方文档。

[翻译] Tensorflow中name scope和variable scope的区别是什么的更多相关文章

  1. Python中变量的作用域(variable scope)

    http://www.crifan.com/summary_python_variable_effective_scope/ 解释python中变量的作用域 示例: 1.代码版 #!/usr/bin/ ...

  2. Tensorflow中的run()函数

    1 run()函数存在的意义 run()函数可以让代码变得更加简洁,在搭建神经网络(一)中,经历了数据集准备.前向传播过程设计.损失函数及反向传播过程设计等三个过程,形成计算网络,再通过会话tf.Se ...

  3. tensorflow变量作用域(variable scope)

    举例说明 TensorFlow中的变量一般就是模型的参数.当模型复杂的时候共享变量会无比复杂. 官网给了一个case,当创建两层卷积的过滤器时,每输入一次图片就会创建一次过滤器对应的变量,但是我们希望 ...

  4. tensorflow variable scope 变量命名空间和变量共享

    import tensorflow as tf def f(): var = tf.Variable(initial_value=tf.random_normal(shape=[2])) return ...

  5. [TensorBoard] Name & Variable scope

    TF有两个scope, 一个是name_scope一个是variable_scope 第一个程序: with tf.name_scope("hello") as name_scop ...

  6. [Ruby] Ruby Variable Scope

    Scope defines where in a program a variable is accessible. Ruby has four types of variable scope, lo ...

  7. PHP Variable Scope

    原文: https://phppot.com/php/variable-scope-in-php/ Last modified on March 24th, 2017 by Vincy. ------ ...

  8. tensorflow中常量(constant)、变量(Variable)、占位符(placeholder)和张量类型转换reshape()

    常量 constant tf.constant()函数定义: def constant(value, dtype=None, shape=None, name="Const", v ...

  9. tensorflow中slim模块api介绍

    tensorflow中slim模块api介绍 翻译 2017年08月29日 20:13:35   http://blog.csdn.net/guvcolie/article/details/77686 ...

随机推荐

  1. 笔记:Struts 2.3.31 配置说明

    复制文件到站点的 WEB-INF\lib 目录,文件列表如下,黄色突出显示的是必须加入的核心包 struts2-core-2.3.31.jar:struts2 的核心库 xwork-core-2.3. ...

  2. JVM学习五:JVM之类加载器之编译常量和主动使用

    在学习了前面几节的内容后,相信大家已经对JAVA 虚拟机 加载类的过程有了一个认识和了解,那么本节,我们就继续进一步巩固前面所学知识和特殊点. 一.类的初始化回顾 类在初始化的时候,静态变量的声明语句 ...

  3. spring-boot 多模块化项目和EurekaServer的搭建

    Spring boot由于其 1.易于开发和维护.2.单个微服务启动快.3.局部修改部署容易.4.技术栈不受语言限制等优点受到越来越多公司的重视.spring-boot还集成了许多关于微服务开发的框架 ...

  4. jenkins忘记密码怎么办?

    在nginx配置文件中加上域名访问,重定向到本机的8080端口. server { listen 80; server_name tomcat.qinyj.top; root /application ...

  5. mysql新手入门随笔

    1.启动/关闭服务器 第一种方法:通过Notifier 第二种方法: 通过Windows自带的服务管理:计算机右键选择管理弹出框选择"服务和应用程序"里的服务列表,从列表中找到My ...

  6. java中的并发工具类

    在jdk的并发包里提供了几个非常有用的并发工具类.CountDownLatdch.CyclicBarrier和Semaphore工具类提供了一种并发流程控制的手段,Exchanger工具类则提供了在线 ...

  7. java使用io创建文件与删除文件的工具类

    java中对于文件的操作,是再常见不过了.以下代码是自己代码中所用到的工具类,仅供参考. import java.io.File; import java.io.IOException; /** * ...

  8. DevOps实践之Jenkins安装部署

    Prerequisites Minimum hardware requirements: 256 MB of RAM 1 GB of drive space (although 10 GB is a ...

  9. 【RabbitMQ系列】 Spring mvc整合RabbitMQ

    一.linux下安装rabbitmq 1.安装erlang环境 wget http://erlang.org/download/otp_src_18.2.1.tar.gz tar xvfz otp_s ...

  10. 第二次作业:APP案例分析

    App案例分析 产品:三国杀-页游手游双通 选择理由 当今社会手机已经渐渐取代了电脑在人们日常生活的需求,既然要选择APP进行案例分析,首推的估计就是手机APP了.三国杀是陪伴我高中时代的主要娱乐方式 ...