Difference between Variable and get_variable in TensorFlow

Difference between Variable and get_variable in TensorFlow

Asked on December 11, 2018 in Tensorflow.
Add Comment


  • 1 Answer(s)

          The Main Difference between Variable and get_variable in TensorFlow are

    • tf.Variable always make a new variable, But tf.get_variable create a new one or get an existing variable from the graph.
    • tf.Variable need an initial value be specified.

          Note to clarify that the function tf.get_variable prefixes the name with the current variable scope to execute reuse checks.

          Example:

    with tf.variable_scope("one"):
        a = tf.get_variable("v", [1]) #a.name == "one/v:0"
    with tf.variable_scope("one"):
        b = tf.get_variable("v", [1]) #ValueError: Variable one/v already exists
    with tf.variable_scope("one", reuse = True):
        c = tf.get_variable("v", [1]) #c.name == "one/v:0"
     
    with tf.variable_scope("two"):
        d = tf.get_variable("v", [1]) #d.name == "two/v:0"
        e = tf.Variable(1, name = "v", expected_shape = [1]) #e.name == "two/v_1:0"
     
    assert(a is c) #Assertion is true, they refer to the same object.
    assert(a is d) #AssertionError: they are different objects
    assert(d is e) #AssertionError: they are different objects
    

          AssertionError means: The two variables with the same name under the same scope are declared to be the same variable. But if you test the names of variables d and e you will note that Tensorflow changed the name of variable e:

    d.name #d.name == "two/v:0"
    e.name #e.name == "two/v_1:0"
    
    Answered on December 11, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.