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 相关文章推荐
python3序列化与反序列化用法实例
May 26 Python
python写日志封装类实例
Jun 28 Python
python去除字符串中的换行符
Oct 11 Python
AI人工智能 Python实现人机对话
Nov 13 Python
Python装饰器用法实例总结
Feb 07 Python
一篇文章读懂Python赋值与拷贝
Apr 19 Python
Python使用Phantomjs截屏网页的方法
May 17 Python
django中ORM模型常用的字段的使用方法
Mar 05 Python
PyCharm 创建指定版本的 Django(超详图解教程)
Jun 18 Python
浅析Python 引号、注释、字符串
Jul 25 Python
python 正则表达式贪婪模式与非贪婪模式原理、用法实例分析
Oct 14 Python
检测tensorflow是否使用gpu进行计算的方式
Feb 03 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
php面向对象全攻略 (十五) 多态的应用
2009/09/30 PHP
解析PHP多种序列化与反序列化的方法
2013/06/06 PHP
如何在Ubuntu下启动Apache的Rewrite功能
2013/07/05 PHP
PHP的反射类ReflectionClass、ReflectionMethod使用实例
2014/08/05 PHP
phpinfo()中Loaded Configuration File(none)的解决方法
2017/01/16 PHP
如何在标题栏显示框架内页面的标题
2007/02/03 Javascript
基于jquery的仿百度的鼠标移入图片抖动效果
2010/09/17 Javascript
基于jquery的二级联动菜单实现代码
2011/04/25 Javascript
用js正确判断用户名cookie是否存在的方法
2014/01/28 Javascript
关闭页面时window.location事件未执行的原因分析及解决方案
2014/09/01 Javascript
PHP结合jQuery实现的评论顶、踩功能
2015/07/22 Javascript
js实现左侧网页tab滑动门效果代码
2015/09/06 Javascript
js+canvas简单绘制圆圈的方法
2016/01/28 Javascript
jQuery日历插件datepicker用法详解
2016/03/03 Javascript
弹出遮罩层后禁止滚动效果【实现代码】
2016/04/29 Javascript
Angularjs根据json文件动态生成路由状态的实现方法
2017/04/17 Javascript
vue 挂载路由到头部导航的方法
2017/11/13 Javascript
javascript实现雪花飘落效果
2020/08/19 Javascript
vue-cli3配置favicon.ico和title的流程
2020/10/27 Javascript
echarts柱状图背景重叠组合而非并列的实现代码
2020/12/10 Javascript
[04:19]完美世界携手游戏风云打造 卡尔工作室模型介绍篇
2013/04/24 DOTA
教你安装python Django(图文)
2013/11/04 Python
python在windows和linux下获得本机本地ip地址方法小结
2015/03/20 Python
python 删除非空文件夹的实例
2018/04/26 Python
mac下如何将python2.7改为python3
2018/07/13 Python
Django文件存储 自己定制存储系统解析
2019/08/02 Python
Python 保持登录状态进行接口测试的方法示例
2019/08/06 Python
python创建ArcGIS shape文件的实现
2019/12/06 Python
pytorch点乘与叉乘示例讲解
2019/12/27 Python
生产内勤岗位职责
2013/12/07 职场文书
医学类个人求职信范文
2014/02/05 职场文书
元旦联欢会感言
2014/03/04 职场文书
毕业生学校推荐信范文
2014/05/21 职场文书
幼儿园六一主持词开场白
2015/05/28 职场文书
公安忠诚教育心得体会
2016/01/23 职场文书
彻底理解golang中什么是nil
2021/04/29 Golang