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中的变量默认是什么类型
Sep 11 Python
python将处理好的图像保存到指定目录下的方法
Jan 10 Python
Python3实现的回文数判断及罗马数字转整数算法示例
Mar 27 Python
Apache,wsgi,django 程序部署配置方法详解
Jul 01 Python
python 的 scapy库,实现网卡收发包的例子
Jul 23 Python
python颜色随机生成器的实例代码
Jan 10 Python
Django 构建模板form表单的两种方法
Jun 14 Python
python利用opencv保存、播放视频
Nov 02 Python
详解Scrapy Redis入门实战
Nov 18 Python
python opencv肤色检测的实现示例
Dec 21 Python
conda安装tensorflow和conda常用命令小结
Feb 20 Python
python中urllib包的网络请求教程
Apr 19 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 CURL用法的深入分析
2013/06/09 PHP
简单的自定义php模板引擎
2016/08/26 PHP
PHP序列化的四种实现方法与横向对比
2018/11/29 PHP
javascript的事件描述
2006/09/08 Javascript
Mootools 1.2教程 Fx.Morph、Fx选项和Fx事件
2009/09/15 Javascript
ajax更新数据后,jquery、jq失效问题
2011/03/16 Javascript
jQuery解决下拉框select设宽度时IE 6/7/8下option超出显示不全
2013/05/27 Javascript
JavaScript使用HTML5的window.postMessage实现跨域通信例子
2014/04/11 Javascript
后台获取ZTREE选中节点的方法
2015/02/12 Javascript
jQuery在页面加载时动态修改图片尺寸的方法
2015/03/20 Javascript
使用jquery清空、复位整个输入域
2015/04/02 Javascript
jQuery.each使用详解
2015/07/07 Javascript
基于Node.js的强大爬虫 能直接发布抓取的文章哦
2016/01/10 Javascript
深入浅析JavaScript中的constructor
2016/04/19 Javascript
浅析如何利用angular结合translate为项目实现国际化
2016/12/08 Javascript
jQuery Ajax请求后台数据并在前台接收
2016/12/10 Javascript
用JavaScript实现让浏览器停止载入页面的方法
2017/01/19 Javascript
JS实现的DIV块来回滚动效果示例
2017/02/07 Javascript
BACKBONE.JS 简单入门范例
2017/10/17 Javascript
微信小程序获取公众号文章列表及显示文章的示例代码
2020/03/10 Javascript
Python实现获取网站PR及百度权重
2015/01/21 Python
Python写入CSV文件的方法
2015/07/08 Python
Python 查找list中的某个元素的所有的下标方法
2018/06/27 Python
SELENIUM自动化模拟键盘快捷键操作实现解析
2019/10/28 Python
Python3交互式shell ipython3安装及使用详解
2020/07/11 Python
迪士尼英国官方商店:shopDisney UK
2019/09/21 全球购物
NFL官方在线商店:NFLShop
2020/07/29 全球购物
JRE、JDK、JVM之间的关系怎样
2012/05/16 面试题
介绍一下EJB的分类及其各自的功能及应用
2016/08/23 面试题
护士毕业自我鉴定
2014/02/07 职场文书
精彩的演讲稿开头
2014/05/08 职场文书
2015年银行信贷员工作总结
2015/05/19 职场文书
老干部局2015年度工作总结
2015/10/22 职场文书
如何判断pytorch是否支持GPU加速
2021/06/01 Python
SQL Server表分区降低运维和维护成本
2022/04/08 SQL Server
请求模块urllib之PYTHON爬虫的基本使用
2022/04/08 Python