TensorFlow变量创建与查找:tf.Variable与tf.get_variable详解
本文详解TensorFlow中tf.Variable与tf.get_variable的区别,涵盖变量命名、共享机制及通过名称查找变量的三种方法。结合Ubuntu14.04与TensorFlow1.4环境,提供代码示例与输出解析,帮助开发者掌握变量管理与模型微调技巧。
运行环境配置为Ubuntu14.04系统,TensorFlow版本为1.4(通过bazel源码编译安装),Python解释器使用Anaconda提供的3.6版本。
在TensorFlow中声明变量主要采用两种方式:tf.Variable和tf.get_variable。两者最核心的区别在于行为机制与用途。
具体差异如下:(1) tf.Variable是一个类,封装了丰富的属性和方法;而tf.get_variable是一个函数。(2) tf.Variable生成的变量名必须唯一,若指定的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中,其默认值为[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))
以上为本文的全部内容,希望对各位的学习有所帮助,也欢迎大家继续支持本站。
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









