1. 程式人生 > >TensorFlow中,variable_scope和name_scope的不同之處

TensorFlow中,variable_scope和name_scope的不同之處

之前一直很困惑,tf.variable_scope和tf.name_scope都是管理上下文環境的,它們有什麼不同?

查閱資料時,發現了一段有意思的測試程式碼

import tensorflow as tf
def scoping(fn, scope1, scope2, vals):
    with fn(scope1):
        a = tf.Variable(vals[0], name='a')
        # 此處注意 b是get_variable
        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]) # 如果加上這一行,就會報錯,因為d3的變數b會和d2的變數b衝突
# d3 = scoping(tf.name_scope, 'scope_name2', 'res', [1, 2, 3]) # 但這一行就不會衝突,因為d3和d1的變數b各自有作用域 # d3 = scoping(tf.variable_scope, 'scope_vars2', '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()

執行後,得到如下輸出

scope_vars
  scope_vars/a:0
  scope_vars/b:0
  scope_vars/c:0
  scope_vars/res/res:0 

scope_name
  scope_name/a:0
  b:0
  scope_name/c:0
  scope_name/res/res:0 

TensorBoard顯示
TensorBoard顯示

總而言之,tf.name_scope僅為非tf.get_variable建立的tensor新增字首;而tf.variable_scope為所有tensor新增字首