tensorflow中name_scopeとvariable_scope変数の使用

21334 ワード

1. variable_scopeの使用
まず、variable_を使いますscopeはgetを簡単に管理できますvaribale.
get_の決定方法variableのprefixed name?
1.1 variable scopeはネストできます.
import tensorflow as tf

with tf.variable_scope("tet1"):
    var3 = tf.get_variable("var3",shape=[2],dtype=tf.float32)
    print (var3.name)
    with tf.variable_scope("tet2"):
        var4 = tf.get_variable("var4",shape=[2],dtype=tf.float32)
        print (var4.name)

出力:
tet1/var3:0
tet1/tet2/var4:0

ファイルを検索するときの完全なパスと同様に、変数のネストされた名前が表示されます.
1.2 get_varibale.name変数を作成するscopeを名前とするprefix
例1:
import tensorflow as tf

def te2():
    with tf.variable_scope("te2"):
        var2 = tf.get_variable("var2",shape=[2], dtype=tf.float32)
        print ('var2.name:',var2.name)
        def te1():
            with tf.variable_scope("te1"):
                var1 = tf.get_variable("var1", shape=[2], dtype=tf.float32)
            return var1
        return te1() # scope te2     

res = te2()
print ('res.name:',res.name)

出力:
var2.name: te2/var2:0
res.name: te2/te1/var1:0

例2:
import tensorflow as tf

def te2():
    with tf.variable_scope("te2"):
        var2 = tf.get_variable("var2",shape=[2], dtype=tf.float32)
        print ('var2.name:',var2.name)
        def te1():
            with tf.variable_scope("te1"):
                var1 = tf.get_variable("var1", shape=[2], dtype=tf.float32)
            return var1
    return te1() # scope te2     

res = te2()
print ('res.name:',res.name)

出力:
var2.name: te2/var2:0
res.name: te1/var1:0

1.3 tf.variable_scope(「name」)とtf.variable_scope(scope)の違い
import tensorflow as tf

with tf.variable_scope("scope"):
    print (tf.get_variable("w",shape=[1]))#     name  scope/w
    with tf.variable_scope("scope"):
       #      name  scope/scope/w,             ,        
       print( tf.get_variable("w", shape=[1]) )

print('........................................')

with tf.variable_scope("yin"):
    print(tf.get_variable("w",shape=[1]))
    scope = tf.get_variable_scope()#     name  yin/w
    print('scope:',scope)
    with tf.variable_scope(scope):#       scope,      scope
        print(tf.get_variable("w", shape=[1]))#     name   yin/w,         ,   
<tf.Variable 'scope/w:0' shape=(1,) dtype=float32_ref>
<tf.Variable 'scope/scope/w:0' shape=(1,) dtype=float32_ref>
........................................
<tf.Variable 'yin/w:0' shape=(1,) dtype=float32_ref>
scope: <tensorflow.python.ops.variable_scope.VariableScope object at 0x12060cd68>
Traceback (most recent call last):

  File "", line 1, in <module>
    runfile('/Users/lilong/Desktop/tensorflow_test/tensorflow_8/variable_use.py', wdir='/Users/lilong/Desktop/tensorflow_test/tensorflow_8')
    ....
    ....
    ValueError: Variable yin/w already exists, disallowed. Did you mean to set reuse=True or reuse=tf.AUTO_REUSE in VarScope? Originally defined at:
    ...

1.4共有変数
共有変数の前提は、変数の名前が同じである、変数の名前は変数名とそのscope接頭辞とからなる、tf.get_variable_scope().reuse_variables()は、現在のscopeの下にあるすべての変数を共有できるようにします.reused_variablesは同じノードを見ることができます.tf.get_variable_scope():現在のscope tf.get_variable_scope().reuse_variables()を取得する:共有変数
import tensorflow as tf

with tf.variable_scope("level1"):
    print(tf.get_variable("w",shape=[1]))
    scope = tf.get_variable_scope()
    print('scope:',scope)
    with tf.variable_scope("level2"):
        print(tf.get_variable("w", shape=[1]))

print('...................')

with tf.variable_scope("level1", reuse=True): #     variable_scope   reuse
    print(tf.get_variable("w",shape=[1]))
    scope = tf.get_variable_scope()
    print('scope:',scope)
    with tf.variable_scope("level2"):
        print(tf.get_variable("w", shape=[1]))

出力:
<tf.Variable 'level1/w:0' shape=(1,) dtype=float32_ref>
scope: <tensorflow.python.ops.variable_scope.VariableScope object at 0x12b470b00>
<tf.Variable 'level1/level2/w:0' shape=(1,) dtype=float32_ref>
...................
<tf.Variable 'level1/w:0' shape=(1,) dtype=float32_ref>
scope: <tensorflow.python.ops.variable_scope.VariableScope object at 0x12b470940>
<tf.Variable 'level1/level2/w:0' shape=(1,) dtype=float32_ref>

1.5 tf.variable_scopeではネーミング競合も処理される場合があります
import tensorflow as tf

def test(name=None):
    #     ,      default_name       variable_scope   ,       
    with tf.variable_scope(name, default_name="scope") as scope:
        w = tf.get_variable("w", shape=[2, 10])

test()
test()
ws = tf.trainable_variables()
for w in ws:
    print(w.name)

出力:
scope/w:0
scope_1/w:0

2 name_scopeの使用
2.1 tensorflowではscopeが2つあり、1つはname_scope一つはvariable_scopeでは、簡単な例で説明します.
例1:
import tensorflow as tf

with tf.name_scope("hello") as name_scope:
    arr1 = tf.get_variable("arr1", shape=[2,10],dtype=tf.float32)
    print ('h1:',name_scope)
    print ('h2:',arr1.name)
    print ("scope_name:%s " % tf.get_variable_scope().original_name_scope)

実行:
h1: hello/
h2: arr1:0
scope_name: 

例2:
import tensorflow as tf;

with tf.variable_scope("hello") as variable_scope:
    arr1 = tf.get_variable("arr1", shape=[2, 10], dtype=tf.float32)

    print ('p1:',variable_scope)      #           
    print ('p2:',variable_scope.name) #          
    print ('p3:',arr1.name)           #      :hello/arr1:0
    print ('p4:',tf.get_variable_scope().original_name_scope) #         
    print ('p6:',tf.get_variable_scope()) #      variable_scope  

    with tf.variable_scope("xixi") as v_scope2:
        print ('p7:',tf.get_variable_scope().original_name_scope)
        print ('p8:',tf.get_variable_scope()) #      v _scope2,         

出力:
p1: .python.ops.variable_scope.VariableScope object at 0x12ccd4b38>
p2: hello
p3: hello/arr1:0
p4: hello/
p6: .python.ops.variable_scope.VariableScope object at 0x12ccd4b38>
p7: hello/xixi/
p8: .python.ops.variable_scope.VariableScope object at 0x12ccd4dd8>

例3:
import tensorflow as tf

with tf.name_scope("name1"):
    with tf.variable_scope("var1"):
        w = tf.get_variable("w",shape=[2])
        res = tf.add(w,[3])

print (w.name)
print (res.name)

出力:
var1/w:0
name1/var1/Add:0
variable_scopename_scopeはopのnameに接頭辞を付けます.これは実際にvariable_が作成されたためです.scopeでは内部に同じ名前のnameが作成されます.scopeは3つのプログラムを比較して見ることができます.
  • name_scopeペアget_variable()で作成する変数の名前には影響はありませんが、作成するopには接頭辞が付けられます.
  • tf.get_variable_scope()が返すのはvariableだけです.scope、nameにかかわらずscope. だから後でtfを使用する.get_variable_scope().reuse_variables()の場合はnameを気にしなくてもいいです.scope

  • 2.2 name_scope作用
    name_scopeはop_へname接頭辞、variable_scopeはget_へvariable()で作成された変数の名前に接頭辞を付ける
    典型的なTensorFlowには数千のノードがあり、このように多くてすべてを見ることが難しく、標準的なグラフツールを使用して展示することもできません.簡単にするために、op/tensor名の範囲を画定し、グラフ内のノードに階層を定義するためにこの情報を可視化します.デフォルトでは、最上位ノードのみが表示されます.以下の例ではtfを用いる.name_scopeはhiddenネーミングドメインの下で3つのアクションを定義します.
    import tensorflow as tf
    
    with tf.name_scope('hidden') as scope:
      a = tf.constant(5, name='alpha')
      W = tf.Variable(tf.random_uniform([1, 2], -1.0, 1.0), name='weights')
      b = tf.Variable(tf.zeros([1]), name='biases')
      print a.name
      print W.name
      print b.name

    出力:
    hidden/alpha 
    hidden/weights 
    hidden/biases 

    2.3 tf.name_scope(None)にはname scopeをクリアする役割があります
    import tensorflow as tf
    with tf.name_scope("hehe"):
        w1 = tf.Variable(1.0)
        with tf.name_scope(None):
            w2 = tf.Variable(2.0)
    print(w1.name)
    print(w2.name)
    
    #hehe/Variable:0
    #Variable:0

    まとめ:1.tfを使用する.Variable()の場合、tf.name_scope()とtf.variable_scope()は、Variableとopのname属性に接頭辞を付けます.2.tfを用いる.get_variable()の場合、tf.name_scope()はtfを与えない.get_variable()で作成されたVariableに接頭辞を付けます.でもtf.Variable()が作成するとname_を受けますscopeの影響
    参照先:https://blog.csdn.net/u012436149/article/details/53018924/ https://blog.csdn.net/u012436149/article/details/53081454