Tensorflow name_scope和variable_scope 的用法

简介

  1. 当一个神经网络比较复杂、参数比较多时,就比较需要一个比较好的方式来传递和管理这些参数。而Tensorflow提供了通过变量名称来创建或者获取变量的机制。通过这个机制,可以在不同的函数中直接通过变量的名称来使用变量,而不需要将变量通过参数进行传递。
  2. name_scope: 为了更好地管理变量的命名空间而提出的。比如在 tensorboard 中,因为引入了 name_scope, 我们的 Graph 看起来才井然有序。
  3. variable_scope: 大部分情况下,跟 tf.get_variable() 配合使用,实现变量共享的功能。

变量创建的三种方式: tf.placeholder, tf.Variable, tf.get_variable

  • 从上面的实验结果来看,这三种方式所定义的变量具有相同的类型。而且只有 tf.get_variable() 创建的变量之间会发生命名冲突。在实际使用中,三种创建变量方式的用途也是分工非常明确的。其中:
  • tf.placeholder() 占位符。 trainable==False
  • tf.Variable() 一般变量用这种方式定义。 可以选择 trainable 类型
  • tf.get_variable() 一般都是和 tf.variable_scope() 配合使用,从而实现变量共享的功能。 可以选择 trainable 类型
  • tf.get_variable的作用不仅在于创建变量,它还可以通过变量名称获取变量,但在创建变量时,如果创建失败(变量已经存在),那么就会报错。因此,就需要一个上下文管理器tf.variable_scope,可以更好的管理变量,并且可以增加程序的可读性。
  • with tf.variable_scope(‘foo’,reuse=None):参数reuse=True时,通过tf.get_variable只能获取已经存在的变量名。上下文管理器在嵌套的时候,变量名称的前面会加上上下文管理器的名称。

探索 name_scope 和 variable_scope

tf.name_scope() 并不会对 tf.get_variable() 创建的变量有任何影响。
tf.name_scope() 主要是用来管理命名空间的,这样子让我们的整个模型更加有条理。而 tf.variable_scope() 的作用是为了实现变量共享,它和 tf.get_variable() 来完成变量共享的功能。

  • 首先我们要确立一种 Graph 的思想。在 TensorFlow 中,我们定义一个变量,相当于往 Graph 中添加了一个节点。和普通的 python 函数不一样,在一般的函数中,我们对输入进行处理,然后返回一个结果,而函数里边定义的一些局部变量我们就不管了。但是在 TensorFlow 中,我们在函数里边创建了一个变量,就是往 Graph 中添加了一个节点。出了这个函数后,这个节点还是存在于 Graph 中的。
  • name_scope 返回的是 string, 而 variable_scope 返回的是对象. 这也可以感觉到, variable_scope 能干的事情比 name_scope 要多.
    • name_scope对 get_variable()创建的变量 的名字不会有任何影响,而创建的op会被加上前缀.
    • tf.get_variable_scope() 返回的只是 variable_scope,不管 name_scope. 所以以后我们在使用
    • tf.get_variable_scope().reuse_variables() 时可以无视name_scope
      总结简单来看
  1. 使用tf.Variable()的时候,tf.name_scope()tf.variable_scope() 都会给 Variableopname属性加上前缀。
  2. 使用tf.get_variable()的时候,tf.name_scope()就不会给 tf.get_variable()创建出来的Variable加前缀。但是 tf.Variable() 创建出来的就会受到 name_scope 的影响.

name_scope可以用来干什么

典型的 TensorFlow 可以有数以千计的节点,如此多而难以一下全部看到,甚至无法使用标准图表工具来展示。为简单起见,我们为op/tensor名划定范围,并且可视化把该信息用于在图表中的节点上定义一个层级。默认情况下, 只有顶层节点会显示。下面这个例子使用tf.name_scope在hidden命名域下定义了三个操作:

import tensorflow as tf
# 创建name前缀hidden
with tf.name_scope('hidden') as scope:# 创建常量a和变量W、ba = tf.constant(5, name='alpha')W = tf.Variable(tf.random_uniform([1, 2], -1.0, 1.0), name='weights')b = tf.Variable(tf.zeros([1]), name='biases')print (a.name)print (W.name)print (b.name)

结果是得到了下面三个操作名:

hidden/alpha:0
hidden/weights:0
hidden/biases:0

name_scope 是给op_name加前缀, variable_scope是给get_variable()创建的变量的名字加前缀。
tf.variable_scope有时也会处理命名冲突

import tensorflow as tf
def test(name=None):# 创建变量名前缀scopewith tf.variable_scope(name, default_name="scope") as scope:# 创建变量名ww = tf.get_variable("w", shape=[2, 10])
test()
test()#会自动处理命名冲突,前缀scope自动加 _1
ws = tf.trainable_variables()
for w in ws:print(w.name)

结果:

scope/w:0
scope_1/w:0 #会自动处理命名冲突

共享变量(共享变量是指共享变量值,而不是共享变量名)

TensorFlow 支持两种共享变量的方式:

  • 显式传递 tf.Variable 对象。
  • tf.variable_scope 对象内隐式包装 tf.Variable 对象。
    虽然显式传递变量的代码非常清晰,但有时编写 TensorFlow 函数(在实现中隐式使用变量)非常方便。tf.layer 中的大多数功能层以及所有 tf.metrics 和部分其他库工具都使用这种方法。
    变量作用域允许您在调用隐式创建和使用变量的函数时控制变量重用。作用域还允许您以分层和可理解的方式命名变量。
    例如,假设我们编写一个函数来创建一个卷积/relu 层:
import tensorflow as tf
# 创建卷积层函数
def conv_relu(input, kernel_shape, bias_shape):# 创建变量名字为 "weights".weights = tf.get_variable("weights", kernel_shape,initializer=tf.random_normal_initializer())# 创建变量名字为 "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)

此函数使用短名称 weightsbiases,这有利于清晰区分二者。然而,在真实模型中,我们需要很多此类卷积层,而且重复调用此函数将不起作用:

input1 = tf.random_normal([1,10,10,32])
input2 = tf.random_normal([1,20,20,32])
x = conv_relu(input1, kernel_shape=[5, 5, 32, 32], bias_shape=[32])
x = conv_relu(x, kernel_shape=[5, 5, 32, 32], bias_shape = [32])  # This fails.

由于期望的操作不清楚(创建新变量还是重新使用现有变量?),因此 TensorFlow 将会失败。不过,在不同作用域内调用 conv_relu 可表明我们想要创建新变量:

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])

如果您想要共享变量,有两种方法可供选择。首先,您可以使用 variable_scopereuse=True 创建具有相同名称的作用域:

with tf.variable_scope("model"):output1 = my_image_filter(input1)
with tf.variable_scope("model", reuse=True):output2 = my_image_filter(input2)

您也可以调用 scope.reuse_variables() 以触发重用:

with tf.variable_scope("model") as scope:output1 = my_image_filter(input1)scope.reuse_variables()output2 = my_image_filter(input2)

由于根据作用域的具体字符串名称初始化变量作用域可能比较危险,因此也可以根据另一作用域进行初始化:

with tf.variable_scope("model") as scope:output1 = my_image_filter(input1)
with tf.variable_scope(scope, reuse=True):output2 = my_image_filter(input2)

Tensorflow name_scope和variable_scope的用法相关推荐

  1. 【TensorFlow-windows】name_scope与variable_scope

    前言 探索一下variable_scope和name_scope相关的作用域,为下一章节tensorboard的学习做准备 其实关于variable_scope与get_variable实现变量共享, ...

  2. tensorflow中name_scope和variable_scope变量的使用

    1. variable_scope的使用 首先,使用variable_scope可以很方便的管理get_varibale. 如何确定 get_variable 的 prefixed name? 1.1 ...

  3. Tensorflow 之 name/variable_scope 变量管理

    name/variable_scope 的作用 充分理解 name / variable_scope TensorFlow 入门笔记 当一个神经网络比较复杂.参数比较多时,就比较需要一个比较好的方式来 ...

  4. tensorflow 代码调试工具tfdbg的用法

    tensorflow 代码调试工具tfdbg的用法 在windows10下安装 使用tfdbg前确定安装好了tensorflow和pyrendline 终端输入 pip install pyreadl ...

  5. TensorFlow学习笔记(1):variable与get_variable, name_scope()和variable_scope()

    Variable tensorflow中有两个关于variable的op,tf.Variable()与tf.get_variable()下面介绍这两个的区别 使用tf.Variable时,如果检测到命 ...

  6. TensorFlow基础笔记(13) tf.name_scope tf.variable_scope学习

    转载http://blog.csdn.net/jerr__y/article/details/60877873 1. 首先看看比较简单的 tf.name_scope('scope_name'). tf ...

  7. Tensorflow中的name_scope和variable_scope

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

  8. tf.name_scope tf.variable_scope学习

    1. 首先看看比较简单的 tf.name_scope('scope_name'). tf.name_scope 主要结合 tf.Variable() 来使用,方便参数命名管理. ''' Signatu ...

  9. tensorflow中batch normalization的用法

    转载网址:如果侵权,联系我删除 https://www.cnblogs.com/hrlnw/p/7227447.html https://www.cnblogs.com/eilearn/p/97806 ...

最新文章

  1. tdd 单元测试_何时给定在单元测试和TDD中的重要性
  2. 掼蛋游戏WEB版——PHP后台实现源码
  3. linux基础之基础命令一
  4. 马斯克获评最鼓舞人心科技领导者,马云排名第5
  5. JDK 1.6环境变量的设置
  6. 【图像处理】【去模糊】图像去模糊的原理
  7. RDD,DataFrame与DataSet区别
  8. QT学习之路:从入门到精通
  9. SPSS统计分析行业应用实战--SPSS 22.0新增
  10. python中len函数_len()函数以及Python中的示例
  11. 华为重回Android,被谷歌移除的华为Mate 20 Pro重回Android Q名单
  12. 鼠标参数以及选购DPI和报告率
  13. 天翼云服务器共享文件夹,天翼云Windows操作解答
  14. 《翻转组件库之init项目》
  15. 经典 Fuzzer 工具 AFL 模糊测试指南
  16. 什么样的护眼灯适合孩子用?真正适合孩子的护眼台灯
  17. csapp程序人生大作业
  18. Infortrend CS分布式NAS集群强项之---成本篇
  19. 教大家如何方便地用百度代理装国外ovi store里的软件--页面不会跳来跳去
  20. 使用Python多线程犯的错误总结

热门文章

  1. int main(int argc,char *argv[]),主函数的参数问题
  2. webpack 配置 babel
  3. Chem. Commun. | 利用基于迁移学习策略的transformer 模型进行Heck反应预测
  4. 从信息时代到智力时代的药物发现
  5. DrugAI | 抗新型冠状病毒药物榜单解析
  6. 【错误总结】Git- remote:error: this exceeds GitHub file size limit of 100.00 MB
  7. 鸿蒙首个云网站,鸿蒙首个云平台服务全中国
  8. python窗体开发环境_Python窗口开发环境boa-constructor教程2:创建状态栏:
  9. 深扒:一个司机如何潜入机房偷数据…
  10. QIIME 2教程. 12数据筛选Filtering data(2021.2)