tensorflow 关键问题辨析

tensorflow中name_scope和variable scope的理解
之所以会出现这两种类型的scope,主要是后者(variable scope)为了实现tensorflow中的变量共享机制:即为了使得在代码的任何部分可以使用某一个已经创建的变量,TF引入了变量共享机制,使得可以轻松的共享变量,而不用传一个变量的引用。具体解释如下:
tf.name_scope() 并不会对 tf.get_variable() 创建的变量有任何影响。
tf.name_scope() 主要是用来管理命名空间的,这样子让我们的整个模型更加有条理。而 tf.variable_scope() 的作用是为了实现变量共享,它和 tf.get_variable() 来完成变量共享的功能。

根据名称查找变量
在创建变量时,即使我们不指定变量名称,程序也会自动进行命名。于是,我们可以很方便的根据名称来查找变量,这在抓取参数、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))

猜你喜欢

转载自www.cnblogs.com/wdmx/p/9649726.html