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利用pyHook实现监听用户鼠标与键盘事件
Aug 21 Python
python中查看变量内存地址的方法
May 05 Python
Python变量和数据类型详解
Feb 15 Python
Python读取sqlite数据库文件的方法分析
Aug 07 Python
Django中Model的使用方法教程
Mar 07 Python
Django使用Mysql数据库已经存在的数据表方法
May 27 Python
Python常用模块os.path之文件及路径操作方法
Dec 03 Python
python 普通克里金(Kriging)法的实现
Dec 19 Python
python 实现屏幕录制示例
Dec 23 Python
Pytorch 搭建分类回归神经网络并用GPU进行加速的例子
Jan 09 Python
python使用多线程+socket实现端口扫描
May 28 Python
Python快速实现一键抠图功能的全过程
Jun 29 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
AJAX for PHP简单表数据查询实例
2007/01/02 PHP
php $_SERVER["REQUEST_URI"]获取值的通用解决方法
2010/06/21 PHP
php插入排序法实现数组排序实例
2015/02/16 PHP
CentOS下搭建PHP环境与WordPress博客程序的全流程总结
2016/05/07 PHP
ajax无刷新动态调用股票信息(改良版)
2008/11/01 Javascript
Jquery中Ajax 缓存带来的影响的解决方法
2011/05/19 Javascript
JQuery each()嵌套使用小结
2014/04/18 Javascript
离开当前页面前使用js判断条件提示是否要离开页面
2014/05/02 Javascript
借助javascript代码判断网页是静态还是伪静态
2014/05/05 Javascript
js获取字符串字节数方法小结
2015/06/09 Javascript
jquery通过name属性取值的简单实现方法
2016/06/20 Javascript
jquery.form.js异步提交表单详解
2017/04/25 jQuery
js解决软键盘遮挡输入框的问题分享
2017/12/19 Javascript
javaScript实现鼠标在文字上悬浮时弹出悬浮层效果
2020/04/12 Javascript
Node.js笔记之process模块解读
2018/05/31 Javascript
vuejs 制作背景淡入淡出切换动画的实例
2018/09/01 Javascript
js html实现计算器功能
2018/11/13 Javascript
Vue 动态添加路由及生成菜单的方法示例
2019/06/20 Javascript
Python使用函数默认值实现函数静态变量的方法
2014/08/18 Python
介绍Python中的一些高级编程技巧
2015/04/02 Python
Python容器使用的5个技巧和2个误区总结
2019/09/26 Python
python topk()函数求最大和最小值实例
2020/04/02 Python
Appium+Python实现简单的自动化登录测试的实现
2021/01/26 Python
HTML5新增的标签和属性归纳总结
2018/05/02 HTML / CSS
Feelunique德国官方网站:欧洲最大的在线美容零售商
2019/07/20 全球购物
介绍一下javax.servlet.Servlet接口及其主要方法
2015/11/30 面试题
周鸿祎:教你写创业计划书
2013/12/30 职场文书
上课玩手机检讨书
2014/02/08 职场文书
充分就业社区汇报材料
2014/05/07 职场文书
纪念九一八事变演讲稿:牢记历史,捍卫主权
2014/09/14 职场文书
2014幼儿园保育员工作总结
2014/11/10 职场文书
2015年社区统计工作总结
2015/04/21 职场文书
新生开学寄语大全
2015/05/28 职场文书
2015中学政教处工作总结
2015/07/22 职场文书
Python趣味爬虫之用Python实现智慧校园一键评教
2021/05/28 Python
win10蓝屏0xc0000001安全模式进不了怎么办?win10出现0xc0000001的解决方法
2022/08/05 数码科技