tensorflow里面共享变量、name_scope, variable_scope等如何理解
tensorflow里面共享变量、name_scope, variable_scope等如何理解
name_scope, variable_scope目的:1 减少训练参数的个数。 2 区别同名变量
为什么要共享变量?我举个简单的例子:例如,当我们研究生成对抗网络GAN的时候,判别器的任务是,如果接收到的是生成器生成的图像,判别器就尝试优化自己的网络结构来使自己输出0,如果接收到的是来自真实数据的图像,那么就尝试优化自己的网络结构来使自己输出1。也就是说,生成图像和真实图像经过判别器的时候,要共享同一套变量,所以TensorFlow引入了变量共享机制。
四个tf.Variable(), tf.get_variable(), tf.Variable_scope(), tf.name_scope()的区别:
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
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等如何理解的更多相关文章
- tensorflow中的name_scope, variable_scope
在训练深度网络时,为了减少需要训练参数的个数(比如LSTM模型),或者是多机多卡并行化训练大数据.大模型等情况时,往往就需要共享变量.另外一方面是当一个深度学习模型变得非常复杂的时候,往往存在大量的变 ...
- tensorflow中使用tf.variable_scope和tf.get_variable的ValueError
ValueError: Variable conv1/weights1 already exists, disallowed. Did you mean to set reuse=True in Va ...
- tensorflow中共享变量 tf.get_variable 和命名空间 tf.variable_scope
tensorflow中有很多需要变量共享的场合,比如在多个GPU上训练网络时网络参数和训练数据就需要共享. tf通过 tf.get_variable() 可以建立或者获取一个共享的变量. tf.get ...
- Tensorflow中的name_scope和variable_scope
Tensorflow是一个编程模型,几乎成为了一种编程语言(里面有变量.有操作......). Tensorflow编程分为两个阶段:构图阶段+运行时. Tensorflow构图阶段其实就是在对图进行 ...
- 关于tensorflow conv2d卷积备忘的一点理解
**************input************** [[[[-0.36166722 0.04847232 1.20818889 -0.1794038 -0.53244466] [ ...
- tensorFlow(一)相关重要函数理解
1.函数及参数:tf.nn.conv2d conv2d( input, filter, strides, padding, use_cudnn_on_gpu=True, data_format='NH ...
- tensorflow/model下的各个参数的理解
首先,这个对应的proto就是 然后config里面的image_resizer等等 就是proto里面的image_resizer 等等,对应的参数可以在proto里面寻找解释和默认值以及类型 再比 ...
- 从锅炉工到AI专家(7)
说说计划 不知不觉写到了第七篇,理一下思路: 学会基本的概念,了解什么是什么不是,当前的位置在哪,要去哪.这是第一篇希望做到的.同时第一篇和第二篇的开始部分,非常谨慎的考虑了非IT专业的读者.希望借此 ...
- tensorflow入门笔记(五) name_scope和variable_scope
一.上下文管理器(context manager) 上下文管理器是实现了上下文协议的对象,主要用于资源的获取与释放.上下文协议包括__enter__.__exit__,简单说就是,具备__enter_ ...
随机推荐
- 【Unity】6.7 向量和Vector3类
分类:Unity.C#.VS2015 创建日期:2016-04-20 一.简介 在虚拟的游戏世界中,与3D有关的数学知识决定了游戏引擎如何计算和模拟出开发者以及玩家看到的每一帧画面.学习或者回想一下基 ...
- go post 上传文件的例子
go post 上传文件 package main import ( "bytes" "fmt" "io" "mime/multi ...
- 菜鸟学Java(十九)——WEB项目测试好帮手,Maven+Jetty
做WEB开发,测试是一件很费时间的事情.所以我们就应该用更简单.更快捷的方式进行测试.今天就向大家介绍一个轻量级的容器——jetty.今天说的etty是Maven的一个插件jetty-maven-pl ...
- CCFollow
// CCFollow // 作用:创建一个跟随动作 // 参数1:跟随的目标对象 // 跟随范围,离开范围就不再跟随 //创建一个参照物spT // CCSprite ...
- raft Paxos
CONSENSUS: BRIDGING THEORY AND PRACTICE https://ramcloud.stanford.edu/~ongaro/thesis.pdf https://web ...
- nginx配置长连接
http { keepalive_timeout 20; --长连接timeout keepalive_requests 8192; --每个连接最大请求数 } events { worker_con ...
- javascript基础拾遗(四)
1.什么是闭包 正常函数,执行完毕后相关的参数,变量就释放掉了. 当一个函数的返回值是另一个函数时,该函数的相关参数和变量都会保存在返回的函数中,这种结构叫做闭包. 2.示例 计算数组和 functi ...
- tensorflow笔记5:tensorflow的基本运作,函数
转载:https://blog.csdn.net/lenbow/article/details/52152766 1.tensorflow的基本运作 为了快速的熟悉TensorFlow编程,下面从一段 ...
- 【原理】Java的ThreadLocal实现原理浅读
当前线程的值传递,ThreadLocal 通过ThreadLocal设值,在线程内可获取,即时获取值时在其它Class或其它Method. public class BasicUsage { priv ...
- Window 分布式 学习2----好文收藏
概述 我们在上一篇Windows平台分布式架构实践 - 负载均衡中讨论了Windows平台下通过NLB(Network Load Balancer) 来实现网站的负载均衡,并且通过压力测试演示了它的效 ...