2016-10-05 13 views
2

私はRNNモデル(rnn.dynamic_rnnメソッドを使用)をトレーニングしており、データマトリックスの形状はnum_examples x max_sequence_length x num_featuresです。トレーニング中は、トレーニング時間とメモリが増加するため、max_sequence_lengthを50または100以上に増やしたくありません。私の訓練セットのすべての文は50未満でした。しかし、テスト中に、モデルは500トークンまで推論することができます。出来ますか?どうすればいいのですか?RNNモデル:トレーニング中に使用される最大シーケンス長より長い文を推論する

答えて

0

@sonal - はい可能です。ほとんどの場合、テストでは、データの束ではなく、単一の例を渡すことに興味があるからです。 だから、あなたが必要なもの、あなたはdynamic_rnnに

test_index = [10 , 23 , 42 ,12 ,24, 50] 

を言う単一の例の配列を渡すことができます必要があります。予測は最終的な隠れた状態に基づいて行われなければならない。 dynamic_rnnの中で、私はあなたがトレーニングでmax_lengthを超えて文を渡すことができると思います。そうでない場合は、GRUまたはLSTM状態を計算するためにカスタムのデコーダ関数を作成し、トレーニング中に取得した重みを使用することができます。アイデアは、テストケースの最大長に達するまで、またはモデルが 'EOS'特別トークンを生成するまで、出力を生成し続けることができるということです。私はエンコーダから最後の隠れた状態を取得した後、デコーダを使用することをお勧めします。これにより、より良い結果も得られます。

# function to the while-loop, for early stopping 
    def decoder_cond(time, state, output_ta_t): 
     return tf.less(time, max_sequence_length) 

    # the body_builder is just a wrapper to parse feedback 
    def decoder_body_builder(feedback=False): 
     # the decoder body, this is where the RNN magic happens! 
     def decoder_body(time, old_state, output_ta_t): 
      # when validating we need previous prediction, handle in feedback 
      if feedback: 
       def from_previous(): 
        prev_1 = tf.matmul(old_state, W_out) + b_out 
        a_max = tf.argmax(prev_1, 1) 
        #### Try to find the token index and stop the condition until you get a EOS token index . 
        return tf.gather(embeddings, a_max) 
       x_t = tf.cond(tf.equal(time, 0), from_previous, lambda: input_ta.read(0)) 
      else: 
       # else we just read the next timestep 
       x_t = input_ta.read(time) 

      # calculate the GRU 
      z = tf.sigmoid(tf.matmul(x_t, W_z_x) + tf.matmul(old_state, W_z_h) + b_z) # update gate 
      r = tf.sigmoid(tf.matmul(x_t, W_r_x) + tf.matmul(old_state, W_r_h) + b_r) # reset gate 
      c = tf.tanh(tf.matmul(x_t, W_c_x) + tf.matmul(r*old_state, W_c_h) + b_c) # proposed new state 
      new_state = (1-z)*c + z*old_state # new state 

      # writing output 
      output_ta_t = output_ta_t.write(time, new_state) 

      # return in "input-to-next-step" style 
      return (time + 1, new_state, output_ta_t) 
     return decoder_body 
    # set up variables to loop with 
    output_ta = tensor_array_ops.TensorArray(tf.float32, size=1, dynamic_size=True, infer_shape=False) 
    time = tf.constant(0) 
    loop_vars = [time, initial_state, output_ta] 

    # run the while-loop for training 
    _, state, output_ta = tf.while_loop(decoder_cond, 
             decoder_body_builder(feedback = True), 
             loop_vars, 
             swap_memory=swap) 

これは単なるスニペットコードであり、それに応じて修正してください。詳細はhttps://github.com/alrojo/tensorflow-tutorial

にあります
関連する問題