How can you re-use a variable scope in tensorflow without a new scope being created by default?

前端 未结 2 917
滥情空心
滥情空心 2021-01-02 11:14

I have created a variable scope in one part of my graph, and later in another part of the graph I want to add OPs to an existing scope. That equates to this distilled exampl

2条回答
  •  囚心锁ツ
    2021-01-02 11:48

    Answer mentioned by kmario23 is correct but there is a tricky case with variables created by tf.get_variable:

    with tf.variable_scope('myscope'):
        print(tf.get_variable('var1', shape=[3]))
    
    with tf.variable_scope('myscope/'):
        print(tf.get_variable('var2', shape=[3]))
    

    This snippet will output:

    
    
    

    It seems that tensorflow has not provided a formal way to handle this circumstance yet. The only possible method I found is to manually assign the correct name (Warning: The correctness is not guaranteed):

    with tf.variable_scope('myscope'):
        print(tf.get_variable('var1', shape=[3]))
    
    with tf.variable_scope('myscope/') as scope:
        scope._name = 'myscope'
        print(tf.get_variable('var2', shape=[3]))
    

    And then we can get the correct names:

    
    
    

提交回复
热议问题