Buscar..


Observaciones

Cuando tiene un modelo enorme, es útil formar algunos grupos de tensores en su gráfico computacional, que están conectados entre sí. Por ejemplo, la clase tf.GraphKeys contiene colecciones estándar tales como:

tf.GraphKeys.VARIABLES
tf.GraphKeys.TRAINABLE_VARIABLES
tf.GraphKeys.SUMMARIES

Crea tu propia colección y úsala para recoger todas tus pérdidas.

Aquí crearemos una colección para las pérdidas del gráfico computacional de la red neuronal.

Primero crea un gráfico computacional así:

with tf.variable_scope("Layer"):
    W = tf.get_variable("weights", [m, k],
        initializer=tf.zeros_initializer([m, k], dtype=tf.float32))
    b1 = tf.get_variable("bias", [k],
        initializer = tf.zeros_initializer([k], dtype=tf.float32))
    z = tf.sigmoid((tf.matmul(input, W) + b1))
    
    with tf.variable_scope("Softmax"):
        U = tf.get_variable("weights", [k, r],
            initializer=tf.zeros_initializer([k,r], dtype=tf.float32))
        b2 = tf.get_variable("bias", [r],
            initializer=tf.zeros_initializer([r], dtype=tf.float32))
    out = tf.matmul(z, U) + b2
cross_entropy = tf.reduce_mean(
    tf.nn.sparse_softmax_cross_entropy_with_logits(out, labels))

Para crear una nueva colección, simplemente puede comenzar a llamar a tf.add_to_collection() : la primera llamada creará la colección.

tf.add_to_collection("my_losses", 
    self.config.l2 * (tf.add_n([tf.reduce_sum(U ** 2), tf.reduce_sum(W ** 2)])))
tf.add_to_collection("my_losses", cross_entropy)

Y finalmente puedes conseguir tensores de tu colección:

loss = sum(tf.get_collection("my_losses"))

Tenga en cuenta que tf.get_collection() devuelve una copia de la colección o una lista vacía si la colección no existe. Además, NO crea la colección si no existe. Para hacerlo, puedes usar tf.get_collection_ref() que devuelve una referencia a la colección y crea una vacía si aún no existe.

Recoger variables de ámbitos anidados

A continuación se muestra una capa oculta de múltiples capas de Perceptrón (MLP) que utiliza el alcance anidado de las variables.

def weight_variable(shape):
    return tf.get_variable(name="weights", shape=shape,
                           initializer=tf.zeros_initializer(dtype=tf.float32))

def bias_variable(shape):
    return tf.get_variable(name="biases", shape=shape,
                           initializer=tf.zeros_initializer(dtype=tf.float32))

def fc_layer(input, in_dim, out_dim, layer_name):
    with tf.variable_scope(layer_name):
        W = weight_variable([in_dim, out_dim])
        b = bias_variable([out_dim])
        linear = tf.matmul(input, W) + b
        output = tf.sigmoid(linear)

with tf.variable_scope("MLP"):
    x = tf.placeholder(dtype=tf.float32, shape=[None, 1], name="x")
    y = tf.placeholder(dtype=tf.float32, shape=[None, 1], name="y")
    fc1 = fc_layer(x, 1, 8, "fc1")
    fc2 = fc_layer(fc1, 8, 1, "fc2")

mse_loss = tf.reduce_mean(tf.reduce_sum(tf.square(fc2 - y), axis=1))

MLP utiliza el nombre de ámbito de nivel superior MLP y tiene dos capas con sus respectivos nombres de alcance fc1 y fc2 . Cada capa también tiene sus propias variables de weights y biases .

Las variables se pueden recoger así:

trainable_var_key = tf.GraphKeys.TRAINABLE_VARIABLES
all_vars = tf.get_collection(key=trainable_var_key, scope="MLP")
fc1_vars = tf.get_collection(key=trainable_var_key, scope="MLP/fc1")
fc2_vars = tf.get_collection(key=trainable_var_key, scope="MLP/fc2")
fc1_weight_vars = tf.get_collection(key=trainable_var_key, scope="MLP/fc1/weights")
fc1_bias_vars = tf.get_collection(key=trainable_var_key, scope="MLP/fc1/biases")

Los valores de las variables se pueden recopilar utilizando el sess.run() . Por ejemplo, si nos gustaría recopilar los valores de fc1_weight_vars después del entrenamiento, podríamos hacer lo siguiente:

sess = tf.Session()
# add code to initialize variables
# add code to train the network
# add code to create test data x_test and y_test

fc1_weight_vals = sess.run(fc1, feed_dict={x: x_test, y: y_test})
print(fc1_weight_vals)  # This should be an ndarray with ndim=2 and shape=[1, 8]


Modified text is an extract of the original Stack Overflow Documentation
Licenciado bajo CC BY-SA 3.0
No afiliado a Stack Overflow