在训练深度网络时,为了减少需要训练参数的个数(比如LSTM模型),或者是多机多卡并行化训练大数据、大模型等情况时,往往就需要共享变量。另外一方面是当一个深度学习模型变得非常复杂的时候,往往存在大量的变量和操作,如何避免这些变量名和操作名的唯一不重复,同时维护一个条理清晰的graph非常重要。因此,tensorflow中用tf.Variable(), tf.get_variable, tf.Variable_scope(), tf.name_scope() 几个函数来实现:

  tf.Variable() 与 tf.get_variable() 的作用与区别:

  1)tf.Variable() 会自动监测命名冲突并自行处理,但是tf.get_variable() 遇到重名的变量创建且没有设置为共享变量时,则会报错。

import tensorflow as tf;

a1 = tf.Variable(tf.random_normal(shape=[2, 3], mean=0, stddev=1), name='a2')

a2 = tf.Variable(tf.random_normal(shape=[2, 3], mean=0, stddev=1), name='a2')

with tf.Session() as sess:
sess.run(tf.initialize_all_variables())
print(a1.name)
print(a2.name) # 输出
a2:0
a2_1:0
import tensorflow as tf;

a1 = tf.get_variable(name='a1', shape=[1], initializer=tf.constant_initializer(1))
a3 = tf.get_variable(name='a1', shape=[1], initializer=tf.constant_initializer(1)) with tf.Session() as sess:
sess.run(tf.initialize_all_variables())
print(a1.name)
print(a3.name) # 输出
ValueError: Variable a1 already exists, disallowed. Did you mean to set reuse=True or reuse=tf.AUTO_REUSE in VarScope? Originally defined at:

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

  

import tensorflow as tf;
import numpy as np; with tf.name_scope('V1'): a1 = tf.Variable(tf.random_normal(shape=[2,3], mean=0, stddev=1), name='a2')
with tf.name_scope('V2'):
a2 = tf.Variable(tf.random_normal(shape=[2,3], mean=0, stddev=1), name='a2') with tf.Session() as sess:
sess.run(tf.initialize_all_variables())
print (a1.name)
print (a2.name) # 输出
V1/a2:0
V2/a2:0
import tensorflow as tf;  

with tf.name_scope('V1'):
a1 = tf.get_variable(name='a1', shape=[1], initializer=tf.constant_initializer(1))
with tf.name_scope('V2'):
a2 = tf.get_variable(name='a1', shape=[1], initializer=tf.constant_initializer(1)) with tf.Session() as sess:
sess.run(tf.initialize_all_variables())
print (a1.name)
print (a2.name) # 输出
Variable a1 already exists, disallowed. Did you mean to set reuse=True in VarScope? Originally defined at:

  3)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.get_variable()配合使用,用于管理一个graph中变量的名字,避免变量之间的命名冲突。

import tensorflow as tf;
import numpy as np; with tf.variable_scope('V1'):
a1 = tf.get_variable(name='a1', shape=[1], initializer=tf.constant_initializer(1))
a2 = tf.Variable(tf.random_normal(shape=[2,3], mean=0, stddev=1), name='a2')
with tf.variable_scope('V2'):
a3 = tf.get_variable(name='a1', shape=[1], initializer=tf.constant_initializer(1))
a4 = tf.Variable(tf.random_normal(shape=[2,3], mean=0, stddev=1), name='a2') with tf.Session() as sess:
sess.run(tf.initialize_all_variables())
print (a1.name)
print (a2.name)
print (a3.name)
print (a4.name) # 输出
V1/a1:0
V1/a2:0
V2/a1:0
V2/a2:0

  4)当要重复使用变量共享时,可以用tf.variable_scope() 和 tf.get_variable()来实现

import tensorflow as tf

with tf.variable_scope('V1', reuse=None):
a1 = tf.get_variable(name='a1', shape=[1], initializer=tf.constant_initializer(1)) with tf.variable_scope('V1', reuse=True):
a2 = tf.get_variable(name='a1', shape=[1], initializer=tf.constant_initializer(1)) with tf.Session() as sess:
sess.run(tf.initialize_all_variables())
print(a1.name)
print(a2.name) #输出
V1/a1:0
V1/a1:0

  上面的代码在第一个variable_scope中的reuse=None,在之后的variable_scope中若是要共享变量,就要将reuse=True。

  

tensorflow中的name_scope, variable_scope的更多相关文章

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

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

  2. Tensorflow中的name_scope和variable_scope

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

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

    tensorflow里面共享变量.name_scope, variable_scope等如何理解 name_scope, variable_scope目的:1 减少训练参数的个数. 2 区别同名变量 ...

  4. [翻译] Tensorflow中name scope和variable scope的区别是什么

    翻译自:https://stackoverflow.com/questions/35919020/whats-the-difference-of-name-scope-and-a-variable-s ...

  5. TensorFlow中的变量命名以及命名空间.

    What: 在Tensorflow中, 为了区别不同的变量(例如TensorBoard显示中), 会需要命名空间对不同的变量进行命名. 其中常用的两个函数为: tf.variable_scope, t ...

  6. tensorflow中slim模块api介绍

    tensorflow中slim模块api介绍 翻译 2017年08月29日 20:13:35   http://blog.csdn.net/guvcolie/article/details/77686 ...

  7. 第二十二节,TensorFlow中的图片分类模型库slim的使用、数据集处理

    Google在TensorFlow1.0,之后推出了一个叫slim的库,TF-slim是TensorFlow的一个新的轻量级的高级API接口.这个模块是在16年新推出的,其主要目的是来做所谓的“代码瘦 ...

  8. 第二十二节,TensorFlow中RNN实现一些其它知识补充

    一 初始化RNN 上一节中介绍了 通过cell类构建RNN的函数,其中有一个参数initial_state,即cell初始状态参数,TensorFlow中封装了对其初始化的方法. 1.初始化为0 对于 ...

  9. 第十八节,TensorFlow中使用批量归一化(BN)

    在深度学习章节里,已经介绍了批量归一化的概念,详情请点击这里:第九节,改善深层神经网络:超参数调试.正则化以优化(下) 神经网络在进行训练时,主要是用来学习数据的分布规律,如果数据的训练部分和测试部分 ...

随机推荐

  1. 【Linux】linux查看日志文件内容命令tail、cat、tac、head、echo

    linux查看日志文件内容命令tail.cat.tac.head.echo tail -f test.log你会看到屏幕不断有内容被打印出来. 这时候中断第一个进程Ctrl-C, ---------- ...

  2. Reinforcement Learning: An Introduction读书笔记(4)--动态规划

     > 目  录 <  Dynamic programming Policy Evaluation (Prediction) Policy Improvement Policy Iterat ...

  3. javascript中数组的常用算法深入分析

    Array数组是Javascript构成的一个重要的部分,它可以用来存储字符串.对象.函数.Number,它是非常强大的.因此深入了解Array是前端必修的功课.本文将给大家详细介绍了javascri ...

  4. Javascript 跨域知识详细介绍

    JS跨域知识总结: 在“跨域”一词经常性地出现以前,我们其实已经频繁地使用它了.如在A网站的img,src指向B网站的某一图片地址,毫无疑问,这在通常情况下都是能正常显示的(且不论防盗链技术):同样, ...

  5. 洛谷P4725 【模板】多项式对数函数(多项式ln)

    题意 题目链接 Sol 这个不用背XD 前置知识: \(f(x) = ln(x), f'(x) = \frac{1}{x}\) \(f(g(x)) = f'(g(x)) g'(x)\) 我们要求的是\ ...

  6. springboot 开发 Tars

    1,创建 springboot 项目,并在启动类添加 @EnableTarsServer 注解 @SpringBootApplication @EnableTarsServer public clas ...

  7. 归并排序(MergeSort)和快速排序(QuickSort)的一些总结问题

    归并排序(MergeSort)和快速排序(QuickSort)都是用了分治算法思想. 所谓分治算法,顾名思义,就是分而治之,就是将原问题分割成同等结构的子问题,之后将子问题逐一解决后,原问题也就得到了 ...

  8. MySQL 性能优化-数据库死锁监控

    MySQL性能优化-数据库死锁监控 by:授客 QQ:1033553122 1)表锁定 通过检查 table_locks_waited 和 table_locks_immediate 状态变量来分析表 ...

  9. this和e.target的异同

    每次触发DOM事件时会产生一个事件对象(也称event对象),此处的参数e接收事件对象.而事件对象也有很多属性和方法,其中target属性是获取触发事件对象的目标,也就是绑定事件的元素,e.targe ...

  10. 2015年6月6日,杨学明老师《IT技术人才管理角色转型与实践》专题培训在苏宁云商成功举办!

    2015.6.6,在中国南京苏宁总部,研发资深顾问.资深讲师为苏宁易购IT事业部全体产品总监.研发总监进行了为期一天的<IT技术人才管理角色转型与实践>的内训服务. 杨学明老师分别从技术人 ...