tensorflow里面共享变量、name_scope, variable_scope等如何理解

  • name_scope, variable_scope目的:1 减少训练参数的个数。 2 区别同名变量

  • 为什么要共享变量?我举个简单的例子:例如,当我们研究生成对抗网络GAN的时候,判别器的任务是,如果接收到的是生成器生成的图像,判别器就尝试优化自己的网络结构来使自己输出0,如果接收到的是来自真实数据的图像,那么就尝试优化自己的网络结构来使自己输出1。也就是说,生成图像和真实图像经过判别器的时候,要共享同一套变量,所以TensorFlow引入了变量共享机制。

    来源:http://www.cnblogs.com/Charles-Wan/p/6200446.html

四个tf.Variable(), tf.get_variable(), tf.Variable_scope(), tf.name_scope()的区别:

  1. tf.Variable()和 tf.get_variable() :

    • tf.Variable()会自动检测命名冲突并自行处理。tf.get_variable()有一个变量检测机制,会检测已经存在的变量时否设置为共享变量,如果已经存在该变量且没有被设置为共享变量,则TensorFlow运行到第二个变量时会报。

    • tf.Variable()和 tf.get_variable()这两种方式都用在一个name_scope下面获取或创建一个变量的两种方式的区别在于:tf.Variable()用于创建一个新变量,在同一个name_scope下可以创建相同名字的变量,底层实现会自动引入别名机制,两次调用产生两个不同的变量。tf.get_variable()用于获取一个变量,并且不受name_scope的约束,当这个变量已经存在,则自动获取,如果不存在,则自动创建一个变量。

    • code解析:

作者:C Li
链接:https://www.zhihu.com/question/54513728/answer/181819324
来源:知乎 '''
1 在tf.name_scope下时,tf.get_variable()创建的变量名不受name_scope的影响,而在未指定共享变量时,如果重名就会报错,tf.Variable()会自动检测有没有变量重名,如果有则会自行处理。
'''
import tensorflow as tf
with tf.name_scope('name_scope_x'):
var1 = tf.get_variable(name='var1', shape=[1], dtype=tf.float32)
var3 = tf.Variable(name='var2', initial_value=[2], dtype=tf.float32)
var4 = tf.Variable(name='var2', initial_value=[2], dtype=tf.float32) with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print(var1.name, sess.run(var1))
print(var3.name, sess.run(var3))
print(var4.name, sess.run(var4))
# 输出结果:
# var1:0 [-0.30036557] 可以看到前面不含有指定的'name_scope_x'
# name_scope_x/var2:0 [ 2.]
# name_scope_x/var2_1:0 [ 2.] 可以看到变量名自行变成了'var2_1',避免了和'var2'冲突 '''
2 使用tf.get_variable()创建变量,且没有设置共享变量,重名时会报错。
'''
import tensorflow as tf
with tf.name_scope('name_scope_1'):
var1 = tf.get_variable(name='var1', shape=[1], dtype=tf.float32)
var2 = tf.get_variable(name='var1', shape=[1], dtype=tf.float32)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print(var1.name, sess.run(var1))
print(var2.name, sess.run(var2)) # ValueError: Variable var1 already exists, disallowed. Did you mean
# to set reuse=True in VarScope? Originally defined at:
# var1 = tf.get_variable(name='var1', shape=[1], dtype=tf.float32) '''
3 共享变量方法,(要共享变量就要使用tf.get_variable(<variable_name>)
'''
import tensorflow as tf
with tf.variable_scope('variable_scope_y') as scope:
var1 = tf.get_variable(name='var1', shape=[1], dtype=tf.float32)
scope.reuse_variables() # 设置共享变量
var1_reuse = tf.get_variable(name='var1')
var2 = tf.Variable(initial_value=[2.], name='var2', dtype=tf.float32)
var2_reuse = tf.Variable(initial_value=[2.], name='var2', dtype=tf.float32) with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print(var1.name, sess.run(var1))
print(var1_reuse.name, sess.run(var1_reuse))
print(var2.name, sess.run(var2))
print(var2_reuse.name, sess.run(var2_reuse))
# 输出结果:
# variable_scope_y/var1:0 [-1.59682846]
# variable_scope_y/var1:0 [-1.59682846] 可以看到变量var1_reuse重复使用了var1
# variable_scope_y/var2:0 [ 2.]
# variable_scope_y/var2_1:0 [ 2.] '''
或者
'''
with tf.variable_scope('foo') as foo_scope:
v = tf.get_variable('v', [1])
with tf.variable_scope('foo', reuse=True):
v1 = tf.get_variable('v')
assert v1 == v '''
或者
'''
with tf.variable_scope('foo') as foo_scope:
v = tf.get_variable('v', [1])
with tf.variable_scope(foo_scope, reuse=True):
v1 = tf.get_variable('v')
assert v1 == v
  1. tf.name_scope()与tf.variable_scope():

    • tf.name_scope()主要用于管理一个图里的各种op,返回的是一个以scope_name命名的context manager。一个graph会维护一个name_space的堆,每一个namespace下面可以定义各种op或者子namespace,实现一种层次化有条理的管理,避免各个op之间命名冲突。

    • tf.variable_scope()一般与tf.name_scope()配合使用,用于管理一个graph中变量的名字,避免变量之间的命名冲突,tf.variable_scope()允许在一个variable_scope下面共享变量。variable_scope的reuse的默认值为False。

    • 通常情况下,tf.variable_scope和tf.name_scope配合,能画出非常漂亮的流程图,但是他们两个之间又有着细微的差别,那就是name_scope只能管住操作ops的名字,而管不住变量Variables的名字。

    with tf.variable_scope("foo"):
    with tf.name_scope("bar"):
    v = tf.get_variable("v", [1])
    x = 1.0 + v
    assert v.name == "foo/v:0"
    assert x.op.name == "foo/bar/add"

tensorflow里面共享变量、name_scope, variable_scope等如何理解的更多相关文章

  1. tensorflow中的name_scope, variable_scope

    在训练深度网络时,为了减少需要训练参数的个数(比如LSTM模型),或者是多机多卡并行化训练大数据.大模型等情况时,往往就需要共享变量.另外一方面是当一个深度学习模型变得非常复杂的时候,往往存在大量的变 ...

  2. tensorflow中使用tf.variable_scope和tf.get_variable的ValueError

    ValueError: Variable conv1/weights1 already exists, disallowed. Did you mean to set reuse=True in Va ...

  3. tensorflow中共享变量 tf.get_variable 和命名空间 tf.variable_scope

    tensorflow中有很多需要变量共享的场合,比如在多个GPU上训练网络时网络参数和训练数据就需要共享. tf通过 tf.get_variable() 可以建立或者获取一个共享的变量. tf.get ...

  4. Tensorflow中的name_scope和variable_scope

    Tensorflow是一个编程模型,几乎成为了一种编程语言(里面有变量.有操作......). Tensorflow编程分为两个阶段:构图阶段+运行时. Tensorflow构图阶段其实就是在对图进行 ...

  5. 关于tensorflow conv2d卷积备忘的一点理解

    **************input************** [[[[-0.36166722  0.04847232  1.20818889 -0.1794038  -0.53244466] [ ...

  6. tensorFlow(一)相关重要函数理解

    1.函数及参数:tf.nn.conv2d conv2d( input, filter, strides, padding, use_cudnn_on_gpu=True, data_format='NH ...

  7. tensorflow/model下的各个参数的理解

    首先,这个对应的proto就是 然后config里面的image_resizer等等 就是proto里面的image_resizer 等等,对应的参数可以在proto里面寻找解释和默认值以及类型 再比 ...

  8. 从锅炉工到AI专家(7)

    说说计划 不知不觉写到了第七篇,理一下思路: 学会基本的概念,了解什么是什么不是,当前的位置在哪,要去哪.这是第一篇希望做到的.同时第一篇和第二篇的开始部分,非常谨慎的考虑了非IT专业的读者.希望借此 ...

  9. tensorflow入门笔记(五) name_scope和variable_scope

    一.上下文管理器(context manager) 上下文管理器是实现了上下文协议的对象,主要用于资源的获取与释放.上下文协议包括__enter__.__exit__,简单说就是,具备__enter_ ...

随机推荐

  1. [100]shell中exec解析

    参考:<linux命令.编辑器与shell编程> <unix环境高级编程> 本地变量可以理解为局部变量,参考:shell基础 参考 bash shell的命令分为两类:外部命令 ...

  2. JAVA中INSTANCEOF关键字的用法总结

    https://www.cnblogs.com/jay36/p/7519145.html https://www.cnblogs.com/zjxynq/p/5882756.html https://b ...

  3. K8s 介绍

    Kubernetes(k8s)是自动化容器操作的开源平台,这些操作包括部署,调度和节点集群间扩展. 使用Kubernetes可以: 1. 自动化容器的部署和复制 2. 随时扩展或收缩容器规模 3. 将 ...

  4. MyBatis传入集合 list 数组 map参数的写法

    foreach的主要用在构建in条件中,它可以在SQL语句中进行迭代一个集合.foreach元素的属性主要有item,index,collection,open,separator,close.ite ...

  5. FFmpeg编译: undefined reference to 'av_frame_alloc()'

    今天使用CMake编译FFmpeg的时候,死活编不过,提示什么“undefined reference to 'av_frame_alloc()” 后来仔细查找,发现是头文件包含错误. 错误的代码: ...

  6. (原创)c++11改进我们的模式之改进代理模式,实现通用的AOP框架

    c++11 boost技术交流群:296561497,欢迎大家来交流技术. 本次要讲的时候如何改进代理模式,具体来说是动态代理模式,动态代理模式一般实现AOP框架,不懂AOP的童鞋看这里.我前面的博文 ...

  7. c++ primer读书笔记之c++11(三)

    1 =default构造函数限定符 c++11针对构造函数提供了=default限定符,可以用于显式指定编译器自动生成特定的构造函数.析构或赋值运算函数.参考代码如下: class CtorDftTy ...

  8. 利用jenkins的api来完成相关工作流程的自动化

    [本文出自天外归云的博客园] 背景 1. 实际工作中涉及到安卓客户端方面的测试,外推或运营部门经常会有很多的渠道,而每个渠道都对应着一个app的下载包,这些渠道都记录在安卓项目下的一个渠道列表文件中. ...

  9. 为python 添加新功能-dump

    一直觉得thinkphp提供的dump函数挺好用的,但是python里面没有,就一直想着写个简单的. dir是我比较常用的一个内置函数了,但是显示效果实在有点受不了,每次我都要从大量的字符串里找到我需 ...

  10. [转]Oracle 树操作(select…start with…connect by…prior)

    原文地址:https://www.cnblogs.com/colder/p/4838574.html oracle树查询的最重要的就是select…start with…connect by…prio ...