【Tensorflow】两种作用域类型tf.name_scope,tf.name_scope

版权声明:本文为博主原创文章,引用时请附上链接。 https://blog.csdn.net/abc13526222160/article/details/86490527

命名域 (name scope),通过tf.name_scope 或 tf.op_scope创建;
变量域 (variable scope),通过tf.name_scope或 tf.variable_op_scope创建;

这两种作用域,对于使用tf.Variable()方式创建的变量,具有相同的效果,都会在变量名称前面,加上域名称
对于通过tf.get_variable()方式创建的变量,只有variable_scope名称会加到变量名称前面,而name_scope不会作为前缀。例如 print(v1.name) # var1:0

例如:

with tf.name_scope("my_name_scope"):
    v1 = tf.get_variable("var1", [1], dtype=tf.float32)
    v2 = tf.Variable(1, name="var2", dtype=tf.float32)

a = tf.add(v1, v2)
print(v1.name) # var1:0
print(v2.name) # my_name_scope/var2:0
print(a.name) # my_name_scope/Add:0

小结:name_scope不会作为tf.get_variable变量的前缀,但是会作为tf.Variable的前缀。

例如:

with tf.variable_scope("my_variable_scope"):
    v1 = tf.get_variable("var1", [1], dtype=tf.float32)
    v2 = tf.Variable(1, name="var2", dtype=tf.float32)

a = tf.add(v1, v2)
print(v1.name) # my_variable_scope/var1:0
print(v2.name) # my_variable_scope/var2:0
print(a.name) # my_variable_scope/Add:0

小结:在variable_scope的作用域下,tf.get_variable()和tf.Variable()都加了scope_name前缀。因此,在tf.variable_scope的作用域下,通过get_variable()可以使用已经创建的变量,实现了变量的共享。

参考作者:https://blog.csdn.net/program_developer/article/details/81138515

猜你喜欢

转载自blog.csdn.net/abc13526222160/article/details/86490527