2017-06-01 1 views
0

Actuellement je le code suivant:Mise à jour de l'état initial d'un réseau de neurones récurrent dans tensorflow

init_state = tf.Variable(tf.zeros([batch_partition_length, state_size])) # -> [16, 1024]. 
final_state = tf.Variable(tf.zeros([batch_partition_length, state_size])) 

And inside my inference method that is responsible producing the output, I have the following: 

def inference(frames): 
    # Note that I write the final_state as a global valriable to avoid the shadowing issue, since it is referenced at the dynamic_rnn line. 
    global final_state 
    # .... Here we have some conv layers and so on... 

    # Now the RNN cell 
    with tf.variable_scope('local1') as scope: 

     # Move everything into depth so we can perform a single matrix multiply. 
     shape_d = pool3.get_shape() 
     shape = shape_d[1] * shape_d[2] * shape_d[3] 
     # tf_shape = tf.stack(shape) 
     tf_shape = 1024 

     print("shape:", shape, shape_d[1], shape_d[2], shape_d[3]) 

     # So note that tf_shape = 1024, this means that we have 1024 features are fed into the network. And 
     # the batch size = 1024. Therefore, the aim is to divide the batch_size into num_steps so that 
     reshape = tf.reshape(pool3, [-1, tf_shape]) 
     # Now we need to reshape/divide the batch_size into num_steps so that we would be feeding a sequence 
     rnn_inputs = tf.reshape(reshape, [batch_partition_length, step_size, tf_shape]) 

     print('RNN inputs shape: ', rnn_inputs.get_shape()) # -> (16, 64, 1024). 

     cell = tf.contrib.rnn.BasicRNNCell(state_size) 
     # note that rnn_outputs are the outputs but not multiplied by W. 
     rnn_outputs, final_state = tf.nn.dynamic_rnn(cell, rnn_inputs, initial_state=init_state) 

    # linear Wx + b 
    with tf.variable_scope('softmax_linear') as scope: 
     weight_softmax = \ 
      tf.Variable(
       tf.truncated_normal([state_size, n_classes], stddev=1/state_size, dtype=tf.float32, name='weight_softmax')) 
     bias_softmax = tf.constant(0.0, tf.float32, [n_classes], name='bias_softmax') 

     softmax_linear = tf.reshape(
      tf.matmul(tf.reshape(rnn_outputs, [-1, state_size]), weight_softmax) + bias_softmax, 
      [batch_size, n_classes]) 

     print('Output shape:', softmax_linear.get_shape()) 

    return softmax_linear 

# Here we define the loss, accuracy and the optimzer. 
# now run the graph: 

with tf.Session() as sess: 
    _, accuracy_train, loss_train, summary = \ 
      sess.run([optimizer, accuracy, cost_scalar, merged], feed_dict={x: image_batch, 
                      y_valence: valences, 
                      confidence_holder: confidences}) 

    .... 

Problème: Comment je serais en mesure d'attribuer initial_state la valeur stockée dans final_state? Autrement dit, comment mettre à jour une valeur Variable plus l'autre?

Je l'ai utilisé comme suit:

tf.assign(init_state, final_state.eval()) 

en séance après l'exécution de la commande sess.run. Mais, cela jette une erreur: Vous devez nourrir une valeur pour « entrées » tenseur d'espace réservé avec DTYPE flotteur Où tf.Variable: « entrée » est déclarée comme suit:

x = tf.placeholder(tf.float32, [None, 112, 112, 3], name='inputs') 

Et l'alimentation se fait après lire les images des tfRecords par la commande suivante:

example = tf.train.Example() 
example.ParseFromString(string_record) 

height = int(example.features.feature['height'] 
      .int64_list 
      .value[0]) 

width = int(example.features.feature['width'] 
      .int64_list 
      .value[0]) 

img_string = (example.features.feature['image_raw'] 
       .bytes_list 
       .value[0]) 

img_1d = np.fromstring(img_string, dtype=np.uint8) 
reconstructed_img = img_1d.reshape((height, width, -1)) # Where this is added to the image_batch list, which is fed into the placeholder. 

Et si essayé ce qui suit:

img_1d = np.fromstring(img_string, dtype=np.float32) 

Cette produira l'erreur suivante:

ValueError: ne peut pas remodeler tableau de taille 9408 en forme (112112, newaxis)

Toute aide est très appréciée !!

Répondre

0

Donc, voici les erreurs que j'ai faites jusqu'à présent. Après avoir fait une certaine révision j'ai compris ce qui suit:

  1. Je ne devrais pas créer le final_state comme tf.Variable. Puisque tf.nn.dynamic_rnn retourne des tenseurs comme ndarray, alors, je ne devrais pas instancier l'état final au début. Et je ne devrais pas utiliser global_state sous la définition de la fonction.

  2. Pour affecter l'état initial du final_state, j'ai utilisé:

    tf.assign(intial_state, final_state) 
    

Et les choses fonctionnent. Note: dans tensorflow, une opération renvoie les données sous forme de tableau numpy dans python et de tensorflow :: Tensor en C et C++. Pour plus d'informations, consultez le https://www.tensorflow.org/versions/r0.10/get_started/basic_usage.