Why do we name variables in Tensorflow?

前端 未结 4 819
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-24 01:53

In some of the places, I saw the syntax, where variables are initialized with names, sometimes without names. For example:

# With name
var = tf.Variable(0, n         


        
4条回答
  •  不知归路
    2020-12-24 02:02

    Consider the following use case code and its output

    def f():
        a = tf.Variable(np.random.normal(), dtype = tf.float32, name = 'test123')
    
    def run123():
        f()
        init = tf.global_variables_initializer()
        with tf.Session() as sess123:
            sess123.run(init)
            print(sess123.run(fetches = ['test123:0']))
            print(sess123.run(fetches = [a]))
    
    run123()
    

    output:

    [0.10108799]

    NameError Traceback (most recent call last) in () 10 print(sess123.run(fetches = [a])) 11 ---> 12 run123()

    in run123() 8 sess123.run(init) 9 print(sess123.run(fetches = ['test123:0'])) ---> 10 print(sess123.run(fetches = [a])) 11 12 run123()

    NameError: name 'a' is not defined

    The 'a', as defined in the scope of f(), not available outside of its scope, i.e in run123(). But the default graph has to refer to them with something, so that the default graph can be referenced to, as needed, across various scopes and that is when its name comes handy.

提交回复
热议问题