声明变量主要有两种方法:<强>特遣部队。变量强>和<强> tf.get_variable >强,二者的最大区别是:
(1)特遣部队。变量是一个类,自带很多属性函数;而tf.get_variable是一个函数;
(2)tf.Variable只能生成独一无二的变量,即如果给出的名字已经存在,则会自动修改生成新的变量名称;
(3)tf.get_variable可以用于生成共享变量。默认情况下,该函数会进行变量名检查,如果有重复则会报错。当在指定变量域中声明可
以变量共享时,可以重复使用该变量(例如RNN中的参数共享)。
下面给出简单的的示例程序:
进口tensorflow特遣部队 与tf.variable_scope (scope1,重用=tf.AUTO_REUSE) scope1: x1=tf.Variable (tf.ones ([1]), name=' x1 ') x2=tf.Variable (tf.zeros ([1]), name=' x1 ') 日元=tf.get_variable(“日元”,初始化=1.0) y2=tf.get_variable(“日元”,初始化=0.0) init=tf.global_variables_initializer () 与tf.Session税(): sess.run (init) 打印(x1.name x1.eval ()) 打印(x2.name x2.eval ()) 打印(y1.name y1.eval ()) 打印(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(…)使用给定初始值来创建一个新变量,该变量会默认添加到图中列出集合,集合的默认为[GraphKeys.GLOBAL_VARIABLES] .
如果可训练的属性被设置为真,该变量同时也会被添加到图收集GraphKeys.TRAINABLE_VARIABLES。
# tf.Variable __init__ ( initial_value=https://www.yisu.com/zixun/None 可训练的=True,=没有集合, validate_shape=True, caching_device=没有 name=没有, variable_def=没有 dtype=没有 expected_shape=没有 import_scope=没有 约束=没有 ) >之前<强> 2。tf.get_variable(…) 强>
tf.get_variable(…)的返回值有两种情形:
使用指定的初始化器来创建一个新变量;
当变量重用时,根据变量名搜索返回一个由特遣部队。get_variable创建的已经存在的变量;
get_variable ( 的名字,=没有形状, dtype=没有 初始值设定项=没有 调整=没有 可训练的=True,=没有集合, caching_device=没有 瓜分者=没有 validate_shape=True, use_resource=没有 custom_getter=没有 约束=没有 ) >之前<强> 3。根据名称查找变量强>
在创建变量时,即使我们不指定变量名称,程序也会自动进行命名。于是,我们可以很方便的根据名称来查找变量,这在抓取参数,整合模型等很多时候都很有用。
通过在tf.global_variables()变量列表中,根据变量名进行匹配搜索查找。该种搜索方式,可以同时找到由tf.Variable或者tf.get_variable创建的变量。
进口tensorflow特遣部队 x=tf.Variable (name=' x ') y=tf.get_variable (name=' y ',形状=[1,2]) 在tf.global_variables var (): 如果var.name==x: 0: 打印(var) >之前
利用get_tensor_by_name()同样可以获得由tf.Variable或者特遣部队。get_variable创建的变量。
需要注意的是,此时获得的是张量,而不是变量,因此x不等于x1。进口tensorflow特遣部队 x=tf.Variable (name=' x ') y=tf.get_variable (name=' y ',形状=[1,2]) 图=tf.get_default_graph () x1=graph.get_tensor_by_name (x: 0) 日元=graph.get_tensor_by_name (y: 0) >之前
针对tf.get_variable创建的变量,可以利用变量重用来直接获取已经存在的变量。
与tf.variable_scope (“foo”): bar1=特遣部队。get_variable(“酒吧”(2、3)#创建 特遣部队。variable_scope (“foo”,重用=True): bar2=tf.get_variable(“酒吧”)#重用 特遣部队。variable_scope(" ",重用=True): # root变量作用域 bar3=tf.get_variable (foo/bar) #重用(相当于上面的) 打印((bar1 bar2)和(bar2 bar3)) >之前tensorflow创建变量以及根据名称查找变量