tensorflow scope理解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import tensorflow as tf
def scoping(fn, scope1, scope2, vals):
with fn(scope1):
a = tf.Variable(vals[0], name='a')
b = tf.get_variable('b', initializer=vals[1])
c = tf.constant(vals[2], name='c')
with fn(scope2):
d = tf.add(a * b, c, name='res')

print '\n '.join([scope1, a.name, b.name, c.name, d.name]), '\n'
return d

d1 = scoping(tf.variable_scope, 'scope_vars', 'res', [1, 2, 3])
d2 = scoping(tf.name_scope, 'scope_name', 'res', [1, 2, 3])

with tf.Session() as sess:
writer = tf.summary.FileWriter('logs', sess.graph)
sess.run(tf.global_variables_initializer())
print sess.run([d1, d2])
writer.close()

从上面的可以看出来,tf.variable_scope()为所有变量(不管你是怎么创建的)、操作(ops)、常量(constant)添加一个前缀,而tf.name_scope()会忽视使用tf.get_variable()创建的变量,因为它假设你知道你使用的变量位于哪个scope中。

请作者喝一杯咖啡☕️