当前位置: 代码迷 >> 综合 >> tf.variable_scope 和 tf.name_scope 的区别
  详细解决方案

tf.variable_scope 和 tf.name_scope 的区别

热度:1   发布时间:2023-10-20 19:56:57.0

这两个函数不仅名称相近,功能上也差不多,不过name_scope的使用范围更小,一般我们都选择variable_scope,下面说下这两个的区别。

我们知道在TensorFlow中每个变量都有自己的作用域,我们常常用作用域+变量名来作为这个变量独一无二的名称。那么,这两个函数就是为了实现这样的功能的。请看下面代码:

import tensorflow as tfwith tf.variable_scope('Cvpr'):var_1 = tf.Variable(0,name='Best_paper')
with tf.name_scope('Eccv'):var_2 = tf.Variable(1,name='Best_paper')sess = tf.Session()
sess.run(tf.initialize_all_variables())
print('var_1 name is',var_1.name)
print('var_2 name is',var_2.name)

结果如下:

var_1 name is Cvpr/Best_paper:0
var_2 name is Eccv/Best_paper:0

注意看,每一个变量之前都scope名称。

那么他们究竟有什么区别呢?这就涉及到另一个函数:tf.get_variable()

import tensorflow as tfwith tf.name_scope('Cvpr'):var_1 = tf.get_variable('Best_paper',[1])
with tf.variable_scope('Eccv'):var_2 = tf.get_variable('Best_paper',[])print('var_1 name is',var_1.name)
print('var_2 name is',var_2.name)

请看输出:

var_1 name is Best_paper:0
var_2 name is Eccv/Best_paper:0

var_1这变量使用get_variable生成的,可以看出get_variable不收tf.name_scope管制。

其实对于大部分TensorFlow使用者,知道name_scope和variable_scope仅仅这一点区别就足够用了。