首页 > 其他 > 详细

tensorflow的变量作用域

时间:2019-07-17 13:51:05      阅读:55      评论:0      收藏:0      [点我收藏+]

一、由来

深度学习中需要使用大量的变量集,以往写代码我们只需要做全局限量就可以了,但在tensorflow中,这样做既不方便管理变量集,有不便于封装,因此tensorflow提供了一种变量管理方法:变量作用域机制

 

二、两个重要API

tf.get_variable(name, shape=None)        # 根据给定的名字创建或返回一个变量

tf.variable_scope(name_or_scope, reuse=None)  # 将name_or_scope下的所有变量组成一个命名空间  

 

三、解读

先说第一个API

tf.get_variable(name, shape=None)这个方法在建立变量时与tf.Variable()完全相同,区别在于它还会搜索是否有同名变量;

1 import tensorflow as tf
2 
3 
4 with tf.variable_scope(const):
5     a = tf.get_variable(a, [1], initializer=tf.constant_initializer(1.))

 

 

再说第二个API

这个方法最重要的参数时reuse,有三个取值:None、True、tf.AUTO_REUSE

reuse = None:继承父类的reuse标志

reuse = True:只能复用,不能创建

 1 import tensorflow as tf
 2 
 3 
 4 with tf.variable_scope(const):
 5     a = tf.get_variable(a, [1])
 6 
 7 with tf.variable_scope(const, reuse=tf.AUTO_REUSE):
 8     b = tf.get_variable(a, [1])
 9 
10 print(a==b)     # True

reuse = tf.AUTO_REUSE:没有就创建,有了就复用,这是最安全的用法

 1 import tensorflow as tf
 2 
 3 
 4 def test():
 5     with tf.variable_scope(const, reuse=tf.AUTO_REUSE):
 6         a = tf.get_variable(a, [1])
 7 
 8     return a
 9 
10 x = test()  # 没有就创建
11 y = test()  # 有了就复用
12 print(x==y)     # True

 

tensorflow的变量作用域

原文:https://www.cnblogs.com/shuaishuaidefeizhu/p/11200269.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!