Cómo hacer la inicialización de Xavier en TensorFlow
Estoy portando mi red Caffe a TensorFlow pero no parece tener inicialización xavier. Estoy usando truncated_normal
pero esto parece estar haciendo que sea mucho más difícil de entrenar.
8 answers
Desde la versión 0.8 hay un inicializador Xavier, ver aquí los documentos.
Puedes usar algo como esto:
W = tf.get_variable("W", shape=[784, 256],
initializer=tf.contrib.layers.xavier_initializer())
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-12-01 16:32:30
Solo para agregar otro ejemplo sobre cómo definir un tf.Variable
inicializado usando el método de Xavier y Yoshua:
graph = tf.Graph()
with graph.as_default():
...
initializer = tf.contrib.layers.xavier_initializer()
w1 = tf.Variable(initializer(w1_shape))
b1 = tf.Variable(initializer(b1_shape))
...
Esto me impidió tener nan
valores en mi función de pérdida debido a inestabilidades numéricas al usar múltiples capas con RELUs.
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
2018-07-07 17:41:57
@Aleph7, la inicialización de Xavier/Glorot depende del número de conexiones entrantes (fan_in), del número de conexiones salientes (fan_out), y del tipo de función de activación (sigmoide o tanh) de la neurona. Vea esto: http://jmlr.org/proceedings/papers/v9/glorot10a/glorot10a.pdf
Así que ahora, a su pregunta. Así es como lo haría en TensorFlow:
(fan_in, fan_out) = ...
low = -4*np.sqrt(6.0/(fan_in + fan_out)) # use 4 for sigmoid, 1 for tanh activation
high = 4*np.sqrt(6.0/(fan_in + fan_out))
return tf.Variable(tf.random_uniform(shape, minval=low, maxval=high, dtype=tf.float32))
Tenga en cuenta que debemos tomar muestras de una distribución uniforme, y no de la distribución normal como se sugiere en el otro respuesta.
Por cierto, escribí un post ayer para algo diferente usando TensorFlow que pasa a usar también la inicialización de Xavier. Si estás interesado, también hay un cuaderno de python con un ejemplo de extremo a extremo: https://github.com/delip/blog-stuff/blob/master/tensorflow_ufp.ipynb
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
2015-11-14 17:43:35
Un buen envoltorio alrededor de tensorflow
llamado prettytensor
da una implementación en el código fuente (copiado directamente desde aquí):
def xavier_init(n_inputs, n_outputs, uniform=True):
"""Set the parameter initialization using the method described.
This method is designed to keep the scale of the gradients roughly the same
in all layers.
Xavier Glorot and Yoshua Bengio (2010):
Understanding the difficulty of training deep feedforward neural
networks. International conference on artificial intelligence and
statistics.
Args:
n_inputs: The number of input nodes into each output.
n_outputs: The number of output nodes for each input.
uniform: If true use a uniform distribution, otherwise use a normal.
Returns:
An initializer.
"""
if uniform:
# 6 was used in the paper.
init_range = math.sqrt(6.0 / (n_inputs + n_outputs))
return tf.random_uniform_initializer(-init_range, init_range)
else:
# 3 gives us approximately the same limits as above since this repicks
# values greater than 2 standard deviations from the mean.
stddev = math.sqrt(3.0 / (n_inputs + n_outputs))
return tf.truncated_normal_initializer(stddev=stddev)
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
2015-12-19 22:25:34
TF-contrib ha xavier_initializer
. Aquí hay un ejemplo de cómo usarlo:
import tensorflow as tf
a = tf.get_variable("a", shape=[4, 4], initializer=tf.contrib.layers.xavier_initializer())
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print sess.run(a)
Además de esto, tensorflow tiene otros inicializadores:
- xavier_initializer_conv2d
- variance_scaling_initializer
- constant_initializer
- zeros_initializer
- ones_initializer
- uniform_unit_scaling_initializer
- truncated_normal_initializer
- random_uniform_initializer
- random_normal_initializer
- orthogonal_initializer
- as así como una gran cantidad de inicializadores de keras
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-05-01 04:00:37
Miré y no pude encontrar nada incorporado. Sin embargo, de acuerdo con esto:
Http://andyljones.tumblr.com/post/110998971763/an-explanation-of-xavier-initialization
La inicialización de Xavier es solo un muestreo de una distribución (generalmente gaussiana) donde la varianza es una función del número de neuronas. tf.random_normal
puede hacer eso por usted, solo necesita calcular el stddev (es decir, el número de neuronas representadas por la matriz de peso que está tratando de inicialización).
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
2015-11-12 19:23:24
A través del parámetro kernel_initializer
a tf.layers.conv2d, tf.layers.conv2d_transpose, tf.layers.Dense
etc
Por ejemplo
layer = tf.layers.conv2d(
input, 128, 5, strides=2,padding='SAME',
kernel_initializer=tf.contrib.layers.xavier_initializer())
Https://www.tensorflow.org/api_docs/python/tf/layers/conv2d
Https://www.tensorflow.org/api_docs/python/tf/layers/conv2d_transpose
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
2018-04-12 13:57:18
En caso de que desee utilizar una línea como lo hace con:
W = tf.Variable(tf.truncated_normal((n_prev, n), stddev=0.1))
Puedes hacer:
W = tf.Variable(tf.contrib.layers.xavier_initializer()((n_prev, n)))
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
2018-05-08 19:19:54