tensorflow创建变量以及根据名称查找变量


Posted in Python onMarch 10, 2018

环境:Ubuntu14.04,tensorflow=1.4(bazel源码安装),Anaconda python=3.6

声明变量主要有两种方法:tf.Variabletf.get_variable,二者的最大区别是:

(1) tf.Variable是一个类,自带很多属性函数;而 tf.get_variable是一个函数;
(2) tf.Variable只能生成独一无二的变量,即如果给出的name已经存在,则会自动修改生成新的变量name;
(3) tf.get_variable可以用于生成共享变量。默认情况下,该函数会进行变量名检查,如果有重复则会报错。当在指定变量域中声明可

以变量共享时,可以重复使用该变量(例如RNN中的参数共享)。
下面给出简单的的示例程序:

import tensorflow as tf

with tf.variable_scope('scope1',reuse=tf.AUTO_REUSE) as scope1:
  x1 = tf.Variable(tf.ones([1]),name='x1')
  x2 = tf.Variable(tf.zeros([1]),name='x1')
  y1 = tf.get_variable('y1',initializer=1.0)
  y2 = tf.get_variable('y1',initializer=0.0)
  init = tf.global_variables_initializer()
  with tf.Session() as sess:
    sess.run(init)
    print(x1.name,x1.eval())
    print(x2.name,x2.eval())
    print(y1.name,y1.eval())
    print(y2.name,y2.eval())

输出结果为:

scope1/x1:0 [ 1.]
scope1/x1_1:0 [ 0.]
scope1/y1:0 1.0
scope1/y1:0 1.0

1. tf.Variable(…)

tf.Variable(…)使用给定初始值来创建一个新变量,该变量会默认添加到 graph collections listed in collections, which defaults to [GraphKeys.GLOBAL_VARIABLES]。

如果trainable属性被设置为True,该变量同时也会被添加到graph collection GraphKeys.TRAINABLE_VARIABLES.

# tf.Variable
__init__(
  initial_value=None,
  trainable=True,
  collections=None,
  validate_shape=True,
  caching_device=None,
  name=None,
  variable_def=None,
  dtype=None,
  expected_shape=None,
  import_scope=None,
  constraint=None
)

2. tf.get_variable(…)

tf.get_variable(…)的返回值有两种情形:

使用指定的initializer来创建一个新变量;
当变量重用时,根据变量名搜索返回一个由tf.get_variable创建的已经存在的变量;

get_variable(
  name,
  shape=None,
  dtype=None,
  initializer=None,
  regularizer=None,
  trainable=True,
  collections=None,
  caching_device=None,
  partitioner=None,
  validate_shape=True,
  use_resource=None,
  custom_getter=None,
  constraint=None
)

3. 根据名称查找变量

在创建变量时,即使我们不指定变量名称,程序也会自动进行命名。于是,我们可以很方便的根据名称来查找变量,这在抓取参数、finetune模型等很多时候都很有用。

示例1:

通过在tf.global_variables()变量列表中,根据变量名进行匹配搜索查找。 该种搜索方式,可以同时找到由tf.Variable或者tf.get_variable创建的变量。

import tensorflow as tf

x = tf.Variable(1,name='x')
y = tf.get_variable(name='y',shape=[1,2])
for var in tf.global_variables():
  if var.name == 'x:0':
    print(var)

示例2:

利用get_tensor_by_name()同样可以获得由tf.Variable或者tf.get_variable创建的变量。
需要注意的是,此时获得的是Tensor, 而不是Variable,因此 x不等于x1.

import tensorflow as tf

x = tf.Variable(1,name='x')
y = tf.get_variable(name='y',shape=[1,2])

graph = tf.get_default_graph()

x1 = graph.get_tensor_by_name("x:0")
y1 = graph.get_tensor_by_name("y:0")

示例3:

针对tf.get_variable创建的变量,可以利用变量重用来直接获取已经存在的变量。

with tf.variable_scope("foo"):
  bar1 = tf.get_variable("bar", (2,3)) # create

with tf.variable_scope("foo", reuse=True):
  bar2 = tf.get_variable("bar") # reuse

with tf.variable_scope("", reuse=True): # root variable scope
  bar3 = tf.get_variable("foo/bar") # reuse (equivalent to the above)

print((bar1 is bar2) and (bar2 is bar3))

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python进程通信之匿名管道实例讲解
Apr 11 Python
Python中死锁的形成示例及死锁情况的防止
Jun 14 Python
Python实现命令行通讯录实例教程
Aug 18 Python
python 写入csv乱码问题解决方法
Oct 23 Python
磁盘垃圾文件清理器python代码实现
Aug 24 Python
PyQt5每天必学之弹出消息框
Apr 19 Python
pycharm修改界面主题颜色的方法
Jan 17 Python
在python Numpy中求向量和矩阵的范数实例
Aug 26 Python
python 消除 futureWarning问题的解决
Dec 25 Python
python程序输出无内容的解决方式
Apr 09 Python
flask开启多线程的具体方法
Aug 02 Python
代码复现python目标检测yolo3详解预测
May 06 Python
Python2中文处理纪要的实现方法
Mar 10 #Python
python实现冒泡排序算法的两种方法
Mar 10 #Python
Python使用pyh生成HTML文档的方法示例
Mar 10 #Python
tensorflow获取变量维度信息
Mar 10 #Python
TensorFlow变量管理详解
Mar 10 #Python
TensorFlow神经网络优化策略学习
Mar 09 #Python
TensorFlow实现AutoEncoder自编码器
Mar 09 #Python
You might like
PHPMailer 中文使用说明小结
2010/01/22 PHP
mysql 查询指定日期时间内sql语句实现原理与代码
2012/12/16 PHP
php中使用$_REQUEST需要注意的一个问题
2013/05/02 PHP
php ckeditor上传图片文件名乱码解决方法
2013/11/15 PHP
php中memcache 基本操作实例
2015/05/17 PHP
PHP创建文件,并向文件中写入数据,覆盖,追加的实现代码
2016/03/25 PHP
PHP编译configure时常见错误的总结
2017/08/17 PHP
JS画5角星方法介绍
2013/09/17 Javascript
js转义字符介绍
2013/11/05 Javascript
浅析在javascript中创建对象的各种模式
2016/05/06 Javascript
Javascript 引擎工作机制详解
2016/11/30 Javascript
BootStrap框架中的data-[ ]自定义属性理解(推荐)
2017/02/14 Javascript
Vue实现自带的过滤器实例
2017/03/09 Javascript
让div运动起来 js实现缓动效果
2017/07/06 Javascript
收藏AngularJS中最重要的核心功能
2017/07/09 Javascript
JavaScript强制类型转换和隐式类型转换操作示例
2019/05/01 Javascript
什么时候不能在 Node.js 中使用 Lock Files
2019/06/24 Javascript
[03:09]DOTA2亚洲邀请赛 LGD战队出场宣传片
2015/02/07 DOTA
Python 深入理解yield
2008/09/06 Python
python中单例常用的几种实现方法总结
2018/10/13 Python
python 对类的成员函数开启线程的方法
2019/01/22 Python
Django 中间键和上下文处理器的使用
2019/03/17 Python
pandas 对日期类型数据的处理方法详解
2019/08/08 Python
Python+OpenCV实现实时眼动追踪的示例代码
2019/11/11 Python
python通过nmap扫描在线设备并尝试AAA登录(实例代码)
2019/12/30 Python
用pandas划分数据集实现训练集和测试集
2020/07/20 Python
Python configparser模块应用过程解析
2020/08/14 Python
纯CSS3实现绘制各种图形实现代码详细整理
2012/12/26 HTML / CSS
canvas环形倒计时组件的示例代码
2018/06/14 HTML / CSS
幼儿园教师考核制度
2014/02/01 职场文书
摄影助理岗位职责
2014/02/07 职场文书
酒店七夕情人节活动策划方案
2014/08/24 职场文书
房产授权委托书范本
2014/09/22 职场文书
领导批评与自我批评范文
2014/10/16 职场文书
汽车质检员岗位职责
2015/04/08 职场文书
道士塔读书笔记
2015/06/30 职场文书