2016-07-07 4 views
18

훈련 된 LSTM 모델이 주어지면 아래의 예에서 단일 시간 간격, 즉 seq_length = 1에 대한 추론을 수행하려고합니다. 각 타임 스텝 후에 내부 LSTM (메모리 및 숨김) 상태는 다음 '일괄 처리'를 위해 기억되어야합니다. 추론의 시작을 위해 입력이 주어진 경우 내부 LSTM 상태 init_c, init_h이 계산됩니다. 그런 다음 LSTM에 전달 된 LSTMStateTuple 개체에 저장됩니다. 훈련 중이 상태는 모든 시간 단계마다 업데이트됩니다. 그러나 추론을 위해 state이 배치 사이에 저장되기를 원합니다. 즉, 초기 상태는 처음부터 계산 될 필요가 있으며 LSTM 상태는 각 '배치'(n = 1) 이후에 저장되어야합니다.TensorFlow : 다음 배치 (스테이트 풀 LSTM)에 대한 LSTM 상태를 기억하십시오.

이 관련된 StackOverflow 질문 : Tensorflow, best way to save state in RNNs?이 발견되었습니다. 그러나 이것은 state_is_tuple=False 인 경우에만 작동하지만 TensorFlow는이 동작이 곧 중단 될 예정입니다 (rnn_cell.py 참조). Keras는 멋진 랩퍼를 사용하여 stateful LSTM이 가능하지만 TensorFlow에서이를 수행하는 가장 좋은 방법을 모르겠습니다. TensorFlow GitHub의이 문제는 또한 내 질문과 관련이 있습니다. https://github.com/tensorflow/tensorflow/issues/2838

누구든지 안정적인 LSTM 모델을 구축하는 데 좋은 제안이 있습니까?

inputs = tf.placeholder(tf.float32, shape=[None, seq_length, 84, 84], name="inputs") 
targets = tf.placeholder(tf.float32, shape=[None, seq_length], name="targets") 

num_lstm_layers = 2 

with tf.variable_scope("LSTM") as scope: 

    lstm_cell = tf.nn.rnn_cell.LSTMCell(512, initializer=initializer, state_is_tuple=True) 
    self.lstm = tf.nn.rnn_cell.MultiRNNCell([lstm_cell] * num_lstm_layers, state_is_tuple=True) 

    init_c = # compute initial LSTM memory state using contents in placeholder 'inputs' 
    init_h = # compute initial LSTM hidden state using contents in placeholder 'inputs' 
    self.state = [tf.nn.rnn_cell.LSTMStateTuple(init_c, init_h)] * num_lstm_layers 

    outputs = [] 

    for step in range(seq_length): 

     if step != 0: 
      scope.reuse_variables() 

     # CNN features, as input for LSTM 
     x_t = # ... 

     # LSTM step through time 
     output, self.state = self.lstm(x_t, self.state) 
     outputs.append(output) 
+2

가능한 [Tensorflow, RNNs에서 상태를 저장하는 가장 좋은 방법은?] (http://stackoverflow.com/questions/37969065/tensorflow-best-way-to-save-state-in-rnns) –

답변

17

모든 레이어의 전체 상태를 자리 표시 자에 저장하는 것이 가장 쉬운 방법이라는 것을 알게되었습니다.

init_state = np.zeros((num_layers, 2, batch_size, state_size)) 

... 

state_placeholder = tf.placeholder(tf.float32, [num_layers, 2, batch_size, state_size]) 

그런 다음 압축을 풀고 기본 tensorflow RNN API를 사용하기 전에 LSTMStateTuples의 튜플을 만듭니다.

l = tf.unpack(state_placeholder, axis=0) 
rnn_tuple_state = tuple(
[tf.nn.rnn_cell.LSTMStateTuple(l[idx][0], l[idx][1]) 
for idx in range(num_layers)] 
) 

RNN은 API에 전달하십시오 state

cell = tf.nn.rnn_cell.LSTMCell(state_size, state_is_tuple=True) 
cell = tf.nn.rnn_cell.MultiRNNCell([cell]*num_layers, state_is_tuple=True) 
outputs, state = tf.nn.dynamic_rnn(cell, x_input_batch, initial_state=rnn_tuple_state) 

- 변수가 다음 자리로 다음 배치에 feeded됩니다.

6

Tensorflow, RNNs에 상태를 저장하는 가장 좋은 방법은 무엇입니까? 실제로 원래의 질문이었습니다. 아래 코드는 내가 상태 튜플을 사용하는 방법이다.

with tf.variable_scope('decoder') as scope: 
    rnn_cell = tf.nn.rnn_cell.MultiRNNCell \ 
    ([ 
     tf.nn.rnn_cell.LSTMCell(512, num_proj = 256, state_is_tuple = True), 
     tf.nn.rnn_cell.LSTMCell(512, num_proj = WORD_VEC_SIZE, state_is_tuple = True) 
    ], state_is_tuple = True) 

    state = [[tf.zeros((BATCH_SIZE, sz)) for sz in sz_outer] for sz_outer in rnn_cell.state_size] 

    for t in range(TIME_STEPS): 
     if t: 
      last = y_[t - 1] if TRAINING else y[t - 1] 
     else: 
      last = tf.zeros((BATCH_SIZE, WORD_VEC_SIZE)) 

     y[t] = tf.concat(1, (y[t], last)) 
     y[t], state = rnn_cell(y[t], state) 

     scope.reuse_variables() 

tf.nn.rnn_cell.LSTMStateTuple을 사용하는 대신 잘 작동하는 목록의 목록을 만듭니다. 이 예제에서는 상태를 저장하지 않습니다. 그러나 쉽게 변수를 국가 밖으로 만들 수 있었고 값을 저장하기 위해 할당을 사용했습니다.

관련 문제