TensorFLow 变量命名空间实例


Posted in Python onFebruary 11, 2020

一、name_scope

with tf.name_scope(name):

name_scope: 为了更好地管理变量的命名空间而提出的。比如在 tensorboard 中,因为引入了 name_scope, 我们的 Graph 看起来才井然有序。

name_scope 对 get_variable 创建变量的 name 没有影响,即 get_variable 创建的变量不在 name_scope 这个命名空间中

二、variable_scope

with tf.variable_scope(name_or_scope, reuse=None):

variable_scope: 大部分情况下,跟 tf.get_variable() 配合使用,实现变量共享的功能

可通过tf.get_variable_scope().reuse == True/False 判断参变量是否共享

当前变量作用域可以用tf.get_variable_scope()进行检索并且reuse 标签可以通过调用tf.get_variable_scope().reuse_variables()设置为True

三、共享参变量

1、方法

使用 tf.Variable() 创建同一个 name 的变量(操作名不同),均不会报错,但系统会自动修改 name(实质还是不让共享参变量)

使用 tf.get_varible() 创建同一个 name 的变量(操作名不同),均会报错(为了避免无意识的参变量复用造成的错误)

我们可以在 variable_scope 中使用 tf.get_variable() 创建变量,并通过 with tf.variable_scope(name_or_scope, reuse=True) 来共享参变量:

reuse=True:将只能获取命名空间中已经创建过的变量,如果变量不存在,则tf.get_variable函数将报错。

reuse=None / False:tf.get_variable操作将创建新的变量,如果同名的变量已经存在,则tf.get_variable函数将报错。

2、代码示例

# 下面是定义一个卷积层的通用方式
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_intializer(0.0))
  conv = tf.nn.conv2d(input, weights,
    strides=[1, 1, 1, 1], padding='SAME')
  return tf.nn.relu(conv + 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])


# 实验一:调用 my_image_filter() 两次
result1 = my_image_filter(image1)
result2 = my_image_filter(image2)
>>> Raises ValueError(... conv1/weights already exists ...), tf.get_variable()会检测已经存在的变量是否已经共享


# 解决方法一, 可以在设计网络时加上一个布尔型的 reuse 参数 
with tf.variable_scope("image_filters"):
  result1 = my_image_filter(image1)
with tf.variable_scope("image_filters", reuse=True):
  result2 = my_image_filter(image2)


# 解决方法二
with tf.variable_scope("image_filters") as scope:
  # 下面我们两次调用 my_image_filter 函数,但是由于引入了变量共享机制
  # 可以看到我们只是创建了一遍网络结构。
  result1 = my_image_filter(image1)
  scope.reuse_variables()
  result2 = my_image_filter(image2)


# 解决方法三
with tf.variable_scope("image_filters") as scope:
  result1 = my_image_filter(image1)
with tf.variable_scope(scope, reuse=True):
  result2 = my_image_filter(image2)


# 打印出所有的可训练参变量
vs = tf.trainable_variables()
print('There are %d trainable_variables in the Graph: ' % len(vs))
for v in vs:
  print(v)


# 输出结果证明确实:参变量共享,因为只有四个变量,没有创建新的变量。
There are 4 trainable_variables in the Graph: 
Tensor("image_filters/conv1/weights/read:0", shape=(5, 5, 32, 32), dtype=float32)
Tensor("image_filters/conv1/biases/read:0", shape=(32,), dtype=float32)
Tensor("image_filters/conv2/weights/read:0", shape=(5, 5, 32, 32), dtype=float32)
Tensor("image_filters/conv2/biases/read:0", shape=(32,), dtype=float32)

四、取出所有可训练参数

# Returns all variables created with trainable=True in a var_list
var_list = tf.trainable_variables()

init = tf.global_variables_initializer()
sess.run(init)

for var in var_list:
  sess.run(var)

以上这篇TensorFLow 变量命名空间实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python使用正则表达式检测密码强度源码分享
Jun 11 Python
浅析Python中的序列化存储的方法
Apr 28 Python
使用SAE部署Python运行环境的教程
May 05 Python
小小聊天室Python代码实现
Aug 17 Python
Python爬取网易云音乐热门评论
Mar 31 Python
利用django如何解析用户上传的excel文件
Jul 24 Python
学习Python selenium自动化网页抓取器
Jan 20 Python
Python系统监控模块psutil功能与经典用法分析
May 24 Python
python利用百度AI实现文字识别功能
Nov 27 Python
python序列类型种类详解
Feb 26 Python
Windows 下python3.8环境安装教程图文详解
Mar 11 Python
利用python查看数组中的所有元素是否相同
Jan 08 Python
TensorFlow 输出checkpoint 中的变量名与变量值方式
Feb 11 #Python
Python中文分词库jieba,pkusegwg性能准确度比较
Feb 11 #Python
pytorch中图像的数据格式实例
Feb 11 #Python
对tensorflow中tf.nn.conv1d和layers.conv1d的区别详解
Feb 11 #Python
python中文分词库jieba使用方法详解
Feb 11 #Python
Transpose 数组行列转置的限制方式
Feb 11 #Python
Tensorflow:转置函数 transpose的使用详解
Feb 11 #Python
You might like
mysql5的sql文件导入到mysql4的方法
2008/10/19 PHP
for循环连续求和、九九乘法表代码
2012/02/20 PHP
浅谈php serialize()与unserialize()的用法
2013/06/05 PHP
PHP资源管理框架Assetic简介
2014/06/12 PHP
ThinkPHP实现将本地文件打包成zip下载
2014/06/26 PHP
PHP PDOStatement对象bindpram()、bindvalue()和bindcolumn之间的区别
2014/11/20 PHP
Yaf框架封装的MySQL数据库操作示例
2019/03/06 PHP
myeclipse安装jQuery插件的方法
2011/03/29 Javascript
jQuery获取注册信息并提示实现代码
2013/04/21 Javascript
jquery获取iframe中的dom对象(两种方法)
2013/07/02 Javascript
web网页按比例显示图片实现原理及js代码
2013/08/09 Javascript
JS实现窗口加载时模拟鼠标移动的方法
2015/06/03 Javascript
JS取数字小数点后两位或n位的简单方法
2016/10/24 Javascript
微信小程序 共用变量值的实现
2017/07/12 Javascript
关于vue单文件中引用路径的处理方法
2018/01/08 Javascript
webpack4 css打包压缩问题的解决
2018/05/18 Javascript
angular将html代码输出为内容的实例
2018/09/30 Javascript
Js跳出两级循环方法代码实例
2020/09/22 Javascript
Python模块学习 datetime介绍
2012/08/27 Python
Python中实现参数类型检查的简单方法
2015/04/21 Python
Django的分页器实例(paginator)
2017/12/01 Python
Python模拟登录的多种方法(四种)
2018/06/01 Python
利用arcgis的python读取要素的X,Y方法
2018/12/22 Python
Python进程间通信 multiProcessing Queue队列实现详解
2019/09/23 Python
Python Flask异步发送邮件实现方法解析
2020/08/01 Python
Python基于Faker假数据构造库
2020/11/30 Python
使用bandit对目标python代码进行安全函数扫描的案例分析
2021/01/27 Python
路易威登和香奈儿手袋:LuxeDH
2017/01/12 全球购物
医学院校毕业生自荐信范文
2014/01/01 职场文书
企业演讲比赛主持词
2014/03/18 职场文书
2016年端午节红领巾广播稿
2015/12/18 职场文书
MySQL时间盲注的五种延时方法实现
2021/05/18 MySQL
在redisCluster中模糊获取key方式
2021/07/09 Redis
面试分析分布式架构Redis热点key大Value解决方案
2022/03/13 Redis
python中的random模块和相关函数详解
2022/04/22 Python
java.util.NoSuchElementException原因及两种解决方法
2022/06/28 Java/Android