首页 技术 正文
技术 2022年11月6日
0 收藏 997 点赞 888 浏览 919 个字

一、由来

深度学习中需要使用大量的变量集,以往写代码我们只需要做全局限量就可以了,但在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()完全相同,区别在于它还会搜索是否有同名变量;

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

再说第二个API

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

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

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

 import tensorflow as tf with tf.variable_scope('const'):
a = tf.get_variable('a', [1]) with tf.variable_scope('const', reuse=tf.AUTO_REUSE):
b = tf.get_variable('a', [1]) print(a==b) # True

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

 import tensorflow as tf def test():
with tf.variable_scope('const', reuse=tf.AUTO_REUSE):
a = tf.get_variable('a', [1]) return a x = test() # 没有就创建
y = test() # 有了就复用
print(x==y) # True
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,082
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,557
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,406
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,179
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,815
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,898