Diferencia entre Variable y get variable en TensorFlow


Por lo que sé, Variable es la operación predeterminada para hacer una variable, y get_variable se usa principalmente para compartir el peso.

Por un lado, hay algunas personas que sugieren usar get_variable en lugar de la operación primitiva Variable siempre que necesite una variable. Por otro lado, simplemente veo cualquier uso de get_variable en los documentos oficiales y demos de TensorFlow.

Por lo tanto, quiero saber algunas reglas de oro sobre cómo utilizar correctamente estos dos mecanismos. ¿Hay algún "estándar" principios?

Author: crizCraig, 2016-05-08

3 answers

Recomiendo usar siempre tf.get_variable(...) make hará que sea mucho más fácil refactorizar su código si necesita compartir variables en cualquier momento, por ejemplo, en una configuración de varias gpu (consulte el ejemplo CIFAR de varias GPU). No tiene ningún inconveniente.

Pure tf.Variable es de nivel inferior; en algún momento tf.get_variable() no existía, por lo que algún código todavía usa la forma de nivel bajo.

 75
Author: Lukasz Kaiser,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-29 09:44:22

Tf.Variable es una clase, y hay varias formas de crear tf.Variable incluyendo tf.Variable.__init__ y tf.get_variable.

Tf.Variable.__init__: Crea una nueva variable con valor_inicial.

W = tf.Variable(<initial-value>, name=<optional-name>)

Tf.get_variable: Obtiene una variable existente con estos parámetros o crea una nueva. También puede usar inicializador.

W = tf.get_variable(name, shape=None, dtype=tf.float32, initializer=None,
       regularizer=None, trainable=True, collections=None)

Es muy útil usar inicializadores como xavier_initializer:

W = tf.get_variable("W", shape=[784, 256],
       initializer=tf.contrib.layers.xavier_initializer())

Más información en https://www.tensorflow.org/versions/r0.8/api_docs/python/state_ops.html#Variable .

 54
Author: Sung Kim,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-08 11:44:33

Puedo encontrar dos diferencias principales entre una y la otra:

  1. Primero es que tf.Variable siempre creará una nueva variable, si tf.get_variable obtiene del gráfico una variable existente con esos parámetros, y si no existe, crea una nueva.

  2. tf.Variable requiere que se especifique un valor inicial.

Es importante aclarar que la función tf.get_variable prefigura el nombre con el ámbito de la variable actual para realizar comprobaciones de reutilización. Por ejemplo:

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

El último error de aserción es interesante: Dos variables con el mismo nombre bajo el mismo ámbito se supone que son la misma variable. Pero si prueba los nombres de las variables d y e se dará cuenta de que Tensorflow cambió el nombre de la variable e:

d.name   #d.name == "two/v:0"
e.name   #e.name == "two/v_1:0"
 29
Author: Jadiel de Armas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-10 15:48:15