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. 【Unity】第6章 Unity脚本开发基础

    分类:Unity.C#.VS2015 创建日期:2016-04-16 一.简介 游戏吸引人的地方在于它的可交互性.如果游戏没有交互,场景做得再美观和精致,也难以称其为游戏. 在Unity中,游戏交互通 ...

  2. Golang IO包的妙用

    Golang 标准库对 IO 的抽象非常精巧,各个组件可以随意组合,可以作为接口设计的典范.这篇文章结合一个实际的例子来和大家分享一下. 背景 以一个RPC的协议包来说,每个包有如下结构 type P ...

  3. HTML5学习笔记(十六):原型、类和继承【JS核心知识点】

    理解原型 在JavaScript中,只要声明了一个函数,就会为该函数创建一个名为prototype的属性,该属性指向当前函数的原型对象. 而函数的原型对象有一个constructor属性,该属性指向刚 ...

  4. 设置Sysctl.conf用以提高Linux的性能(最完整的sysctl.conf优化方案)

    Sysctl是一个允许您改变正在运行中的Linux系统的接口.它包含一些 TCP/IP 堆栈和虚拟内存系统的高级选项, 这可以让有经验的管理员提高引人注目的系统性能.用sysctl可以读取设置超过五百 ...

  5. 解决jar格式文件,双击不能直接运行问题

    前提:  安装了JDK 步骤: 1.先右击jar文件,打开方式->选择默认程序->浏览,选中jre下bin文件中javaw.exe(比如我的javaw.exe在C:\Program Fil ...

  6. 每日英语:How the College Bubble Will Pop

    The American political class has long held that higher education is vital to individual and national ...

  7. Kudu:支持快速分析的新型Hadoop存储系统

    Kudu 是 Cloudera 开源的新型列式存储系统,是 Apache Hadoop 生态圈的新成员之一( incubating ),专门为了对快速变化的数据进行快速的分析,填补了以往 Hadoop ...

  8. 【Java】HashTable和HashMap区别

    ①继承不同 public class Hashtable extends Dictionary implements Map public class HashMap extends Abstract ...

  9. C#学习笔记(15)——c#接口

    说明(2017-7-17 21:57:26): 原文:http://www.cnblogs.com/jiajiayuan/archive/2011/09/16/2178462.html 本文意在巩固基 ...

  10. NLP自然语言处理 jieba中文分词,关键词提取,词性标注,并行分词,起止位置,文本挖掘,NLP WordEmbedding的概念和实现

    1. NLP 走近自然语言处理 概念 Natural Language Processing/Understanding,自然语言处理/理解 日常对话.办公写作.上网浏览 希望机器能像人一样去理解,以 ...