TensorFlow 使用变量共享
参考: https://www.tensorflow.org/programmers_guide/variable_scope
举例说明
TensorFlow中的变量一般就是模型的参数。当模型复杂的时候共享变量会无比复杂。
官网给了一个case,当创建两层卷积的过滤器时,每输入一次图片就会创建一次过滤器对应的变量,但是我们希望所有图片都共享同一过滤器变量,一共有4个变量:conv1_weights, conv1_biases, conv2_weights, and conv2_biases。
通常的做法是将这些变量设置为全局变量。但是存在的问题是打破封装性,这些变量必须文档化被其他代码文件引用,一旦代码变化,调用方也可能需要变化。还有一种保证封装性的方式是将模型封装成类。
不过TensorFlow提供了Variable Scope 这种独特的机制来共享变量。这个机制涉及两个主要函数:
#创建或返回给定名称的变量
tf.get_variable(<name>, <shape>, <initializer>) #管理传给get_variable()的变量名称的作用域
tf.variable_scope(<scope_name>)
在下面的代码中,通过tf.get_variable()创建了名称分别为weights和biases的两个变量。
def conv_relu(input, kernel_shape, bias_shape):
# Create variable named "weights".
weights = tf.get_variable("weights", kernel_shape,
initializer=tf.random_normal_initializer())
# Create variable named "biases".
biases = tf.get_variable("biases", bias_shape,
initializer=tf.constant_initializer(0.0))
conv = tf.nn.conv2d(input, weights,
strides=[1, 1, 1, 1], padding='SAME')
return tf.nn.relu(conv + biases)
但是我们需要两个卷积层,这时可以通过tf.variable_scope()指定作用域进行区分,如with tf.variable_scope("conv1")这行代码指定了第一个卷积层作用域为conv1,在这个作用域下有两个变量weights和biases。
def my_image_filter(input_images):
with tf.variable_scope("conv1"):
# Variables created here will be named "conv1/weights", "conv1/biases".
relu1 = conv_relu(input_images, [5, 5, 32, 32], [32])
with tf.variable_scope("conv2"):
# Variables created here will be named "conv2/weights", "conv2/biases".
return conv_relu(relu1, [5, 5, 32, 32], [32])
最后在image_filters这个作用域重复使用第一张图片输入时创建的变量,调用函数reuse_variables(),代码如下:
with tf.variable_scope("image_filters") as scope:
result1 = my_image_filter(image1)
scope.reuse_variables()
result2 = my_image_filter(image2)
tf.get_variable()工作机制
tf.get_variable()工作机制是这样的:
当tf.get_variable_scope().reuse == False,调用该函数会创建新的变量
with tf.variable_scope("foo"):
v = tf.get_variable("v", [1])
assert v.name == "foo/v:0"当tf.get_variable_scope().reuse == True,调用该函数会重用已经创建的变量
with tf.variable_scope("foo"):
v = tf.get_variable("v", [1])
with tf.variable_scope("foo", reuse=True):
v1 = tf.get_variable("v", [1])
assert v1 is v
变量都是通过作用域/变量名来标识,后面会看到作用域可以像文件路径一样嵌套。
tf.variable_scope理解
tf.variable_scope()用来指定变量的作用域,作为变量名的前缀,支持嵌套,如下:
with tf.variable_scope("foo"):
with tf.variable_scope("bar"):
v = tf.get_variable("v", [1])
assert v.name == "foo/bar/v:0"
当前环境的作用域可以通过函数tf.get_variable_scope()获取,并且reuse标志可以通过调用reuse_variables()设置为True,这个非常有用,如下
with tf.variable_scope("foo"):
v = tf.get_variable("v", [1])
tf.get_variable_scope().reuse_variables()
v1 = tf.get_variable("v", [1])
assert v1 is v
作用域中的resuse默认是False,调用函数reuse_variables()可设置为True,一旦设置为True,就不能返回到False,并且该作用域的子空间reuse都是True。如果不想重用变量,那么可以退回到上层作用域,相当于exit当前作用域,如
with tf.variable_scope("root"):
# At start, the scope is not reusing.
assert tf.get_variable_scope().reuse == False
with tf.variable_scope("foo"):
# Opened a sub-scope, still not reusing.
assert tf.get_variable_scope().reuse == False
with tf.variable_scope("foo", reuse=True):
# Explicitly opened a reusing scope.
assert tf.get_variable_scope().reuse == True
with tf.variable_scope("bar"):
# Now sub-scope inherits the reuse flag.
assert tf.get_variable_scope().reuse == True
# Exited the reusing scope, back to a non-reusing one.
assert tf.get_variable_scope().reuse == False
一个作用域可以作为另一个新的作用域的参数,如:
with tf.variable_scope("foo") as foo_scope:
v = tf.get_variable("v", [1])
with tf.variable_scope(foo_scope):
w = tf.get_variable("w", [1])
with tf.variable_scope(foo_scope, reuse=True):
v1 = tf.get_variable("v", [1])
w1 = tf.get_variable("w", [1])
assert v1 is v
assert w1 is w
不管作用域如何嵌套,当使用with tf.variable_scope()打开一个已经存在的作用域时,就会跳转到这个作用域。
with tf.variable_scope("foo") as foo_scope:
assert foo_scope.name == "foo"
with tf.variable_scope("bar"):
with tf.variable_scope("baz") as other_scope:
assert other_scope.name == "bar/baz"
with tf.variable_scope(foo_scope) as foo_scope2:
assert foo_scope2.name == "foo" # Not changed.
variable scope的Initializers可以创递给子空间和tf.get_variable()函数,除非中间有函数改变,否则不变。
with tf.variable_scope("foo", initializer=tf.constant_initializer(0.4)):
v = tf.get_variable("v", [1])
assert v.eval() == 0.4 # Default initializer as set above.
w = tf.get_variable("w", [1], initializer=tf.constant_initializer(0.3)):
assert w.eval() == 0.3 # Specific initializer overrides the default.
with tf.variable_scope("bar"):
v = tf.get_variable("v", [1])
assert v.eval() == 0.4 # Inherited default initializer.
with tf.variable_scope("baz", initializer=tf.constant_initializer(0.2)):
v = tf.get_variable("v", [1])
assert v.eval() == 0.2 # Changed default initializer.
算子(ops)会受变量作用域(variable scope)影响,相当于隐式地打开了同名的名称作用域(name scope),如+这个算子的名称为foo/add
with tf.variable_scope("foo"):
x = 1.0 + tf.get_variable("v", [1])
assert x.op.name == "foo/add"
除了变量作用域(variable scope),还可以显式打开名称作用域(name scope),名称作用域仅仅影响算子的名称,不影响变量的名称。另外如果tf.variable_scope()传入字符参数,创建变量作用域的同时会隐式创建同名的名称作用域。如下面的例子,变量v的作用域是foo,而算子x的算子变为foo/bar,因为有隐式创建名称作用域foo
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"
注意: 如果tf.variable_scope()传入的不是字符串而是scope对象,则不会隐式创建同名的名称作用域。
TensorFlow 使用变量共享的更多相关文章
- TensorFlow学习笔记3——变量共享
因为最近在研究生成对抗网络GAN,在读别人的代码时发现了 with tf.variable_scope(self.name_scope_conv, reuse = reuse): 这样一条语句,查阅官 ...
- TensorFlow学习笔记4——变量共享
因为最近在研究生成对抗网络GAN,在读别人的代码时发现了 with tf.variable_scope(self.name_scope_conv, reuse = reuse): 这样一条语句,查阅官 ...
- TF Boys (TensorFlow Boys ) 养成记(三): TensorFlow 变量共享
上次说到了 TensorFlow 从文件读取数据,这次我们来谈一谈变量共享的问题. 为什么要共享变量?我举个简单的例子:例如,当我们研究生成对抗网络GAN的时候,判别器的任务是,如果接收到的是生成器生 ...
- 如何在Exe和BPL插件中实现公共变量共享及窗口溶入技术Demo源码
如何在Exe和BPL插件中实现公共变量共享及窗口溶入技术Demo源码 1.Delphi编译方式介绍: 当我们在开发一个常规应用程序时,Delphi可以让我们用两种方式使用VCL,一种是把VCL中的申明 ...
- TF:Tensorflow定义变量+常量,实现输出计数功能—Jason niu
#TF:Tensorflow定义变量+常量,实现输出计数功能 import tensorflow as tf state = tf.Variable(0, name='Parameter_name_c ...
- c++ 变量共享内存-联合(union)
共享内存极少使用,所以这里我们仅作了解. .将几个变量放在相同的内存区,但其中只有一个变量在给定时刻有有效值. .程序处理许多不同类型的数据,但是一次只处理一种.要处理的类型在执行期间才能确定. .在 ...
- 多线程篇四:ThreadLocal实现线程范围内变量共享
1.static实现线程范围内变量共享 package com.test.shareData; import java.util.Random; /** * 多线程范围内的数据共享 * @author ...
- tensorflow variable scope 变量命名空间和变量共享
import tensorflow as tf def f(): var = tf.Variable(initial_value=tf.random_normal(shape=[2])) return ...
- 118、TensorFlow变量共享(二)
import tensorflow as tf # 在不同的变量域中调用conv_relu,并且声明我们想创建新的变量 def my_image_filter(input_images): with ...
随机推荐
- windows下安装mysql
windows 下安装mysql 1.先下载好 mysql5.7 版本的安装包,可以去官网自己下载,也可以从我的百度云分享 里面下载: 链接: https://pan.baidu.com/s/1VXk ...
- C#从http上拿返回JSON数据
C#如何拿到从http上返回JSON数据? 第一章:C#如何拿到从http上返回JSON数据? 第二章:C#如何解析JSON数据?(反序列化对象) 第三章:C#如何生成JSON字符串?(序列化对象) ...
- Cs231n课堂内容记录-Lecture2-Part2 线性分类
Lecture 3 课程内容记录:(上)https://zhuanlan.zhihu.com/p/20918580?refer=intelligentunit (中)https://zhuanlan. ...
- JAVA 容易忽略的东西
Java中的取余会出现负数.用Math.floorMod()方法可以掰正,但是也仅限被除数是负数的情况,如果除数是负数,这个没用. 和C不一样,Java中的字符串是不可变字符串,不能修改Java字符串 ...
- jvisualVM的使用
jvisualvm能干什么:监控内存泄露,跟踪垃圾回收,执行时内存.cpu分析,线程分析... jvisualvm已经被集成在jdk1.6以上的版本中(不是jre).自身运行需要最低jdk1.6版本, ...
- 制作CSS绚烂效果的三种属性
animation(动画).transition(过渡).transform(变形) https://www.cnblogs.com/shenfangfang/p/5713564.html
- dp Surf
题目:https://vj.69fa.cn/1fc993e7e0e1e6fa7ce4640b8d46ef8d?v=1552762626 这个题目和尼克的任务这个题目很像,这个题目因为同一时刻具有选择性 ...
- 在django中如何通过已有的mysql表生成django的model
第一步:先是在项目中建立一个app:python manage.py startapp app01 第二步:python manage.py inspectdb > app01/models.p ...
- 6.05-btc
import requests from lxml import etree import json class BtcSpider(object): def __init__(self): self ...
- Python:Day45 Javascript的String字符串
typeof只能判断普通数据类型, 对于复杂的只是判断出来是一个Object: instanceof 可以判断数据是否是某一类型: alert(s instanceof String); String ...