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实现简单QQ单用户机器人的方法
Jul 03 Python
python获取标准北京时间的方法
Mar 24 Python
python中map、any、all函数用法分析
Apr 21 Python
python简单获取数组元素个数的方法
Jul 13 Python
Python的Flask框架应用调用Redis队列数据的方法
Jun 06 Python
python递归查询菜单并转换成json实例
Mar 27 Python
Python中模块与包有相同名字的处理方法
May 05 Python
python 多线程对post请求服务器测试并发的方法
Jun 13 Python
简单了解python 邮件模块的使用方法
Jul 24 Python
使用python制作游戏下载进度条的代码(程序说明见注释)
Oct 24 Python
python能做哪些生活有趣的事情
Sep 09 Python
只用20行Python代码实现屏幕录制功能
Jun 02 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
从MySQL数据库表中取出随机数据的代码
2007/09/05 PHP
探讨PHP JSON中文乱码的解决方法详解
2013/06/06 PHP
深入PHP curl参数的详解
2013/06/17 PHP
使用PHP接收POST数据,解析json数据
2013/06/28 PHP
PHP实现绘制3D扇形统计图及图片缩放实例
2014/10/01 PHP
php导入模块文件分享
2015/03/17 PHP
codeigniter中view通过循环显示数组数据的方法
2015/03/20 PHP
php递归删除指定文件夹的方法小结
2015/04/20 PHP
Laravel 队列使用的实现
2019/01/08 PHP
PHP调用全国天气预报数据接口查询天气示例
2019/02/20 PHP
查询绑定数据岛的表格中的文本并修改显示方式的js代码
2009/12/15 Javascript
jQuery Autocomplete自动完成插件
2010/07/17 Javascript
JavaScript通过prototype给对象定义属性用法实例
2015/03/23 Javascript
全面解析jQuery $(document).ready()和JavaScript onload事件
2016/06/08 Javascript
js基本算法:冒泡排序,二分查找的简单实例
2016/10/08 Javascript
vue 设置路由的登录权限的方法
2018/07/03 Javascript
vue element中axios下载文件(后端Python)
2019/05/10 Javascript
手写Vue弹窗Modal的实现代码
2019/09/11 Javascript
在JavaScript中实现链式调用的实现
2019/12/24 Javascript
JS中锚点链接点击平滑滚动并自由调整到顶部位置
2021/02/06 Javascript
python django集成cas验证系统
2014/07/14 Python
python获取当前用户的主目录路径方法(推荐)
2017/01/12 Python
详谈Python2.6和Python3.0中对除法操作的异同
2017/04/28 Python
利用Python如何批量更新服务器文件
2018/07/29 Python
pyenv与virtualenv安装实现python多版本多项目管理
2019/08/17 Python
pandas 缺失值与空值处理的实现方法
2019/10/12 Python
python 字典访问的三种方法小结
2019/12/05 Python
写一个方法1000的阶乘
2012/11/21 面试题
计算机学生的自我评价分享
2014/02/18 职场文书
环保建议书
2014/03/12 职场文书
房屋转让协议书范本
2014/04/11 职场文书
感恩的演讲稿
2014/05/06 职场文书
门卫岗位职责
2015/02/09 职场文书
2015年派出所民警工作总结
2015/04/24 职场文书
2016年12月份红领巾广播稿
2015/12/21 职场文书
win10清理dns缓存
2022/04/19 数码科技