2017-06-22 127 views
2

我的理解是,tf.nn.dynamic_rnn返回在每个时间步的RNN单元(例如LSTM)的输出以及最终状态。我如何在所有时间步骤中访问单元状态,而不仅仅是最后一步?例如,我希望能够平均所有隐藏状态,然后在后续图层中使用它。Tensorflow,如何访问一个RNN的所有中间状态,而不仅仅是最后一个状态

以下是我如何定义LSTM单元,然后使用tf.nn.dynamic_rnn展开它。但是这只给出了LSTM的最后一个单元状态。

import tensorflow as tf 
import numpy as np 

# [batch-size, sequence-length, dimensions] 
X = np.random.randn(2, 10, 8) 
X[1,6:] = 0 
X_lengths = [10, 6] 

cell = tf.contrib.rnn.LSTMCell(num_units=64, state_is_tuple=True) 

outputs, last_state = tf.nn.dynamic_rnn(
    cell=cell, 
    dtype=tf.float64, 
    sequence_length=X_lengths, 
    inputs=X) 
sess = tf.InteractiveSession() 
sess.run(tf.global_variables_initializer())         
out, last = sess.run([outputs, last_state], feed_dict=None) 
+0

没有理由需要访问不属于输出结果的内部状态。如果这是您的使用案例,我会考虑定义一个与LSTM相同的RNN,但输出其完整状态。 – jasekp

+0

看看这个QA:https://stackoverflow.com/q/39716241/4282745 – npf

+0

或这个https://github.com/tensorflow/tensorflow/issues/5731#issuecomment-262151359 – npf

回答

1

这样的事情应该工作。

import tensorflow as tf 
import numpy as np 


class CustomRNN(tf.contrib.rnn.LSTMCell): 
    def __init__(self, *args, **kwargs): 
     kwargs['state_is_tuple'] = False # force the use of a concatenated state. 
     returns = super(CustomRNN, self).__init__(*args, **kwargs) # create an lstm cell 
     self._output_size = self._state_size # change the output size to the state size 
     return returns 
    def __call__(self, inputs, state): 
     output, next_state = super(CustomRNN, self).__call__(inputs, state) 
     return next_state, next_state # return two copies of the state, instead of the output and the state 

X = np.random.randn(2, 10, 8) 
X[1,6:] = 0 
X_lengths = [10, 10] 

cell = CustomRNN(num_units=64) 

outputs, last_states = tf.nn.dynamic_rnn(
    cell=cell, 
    dtype=tf.float64, 
    sequence_length=X_lengths, 
    inputs=X) 

sess = tf.InteractiveSession() 
sess.run(tf.global_variables_initializer())         
states, last_state = sess.run([outputs, last_states], feed_dict=None) 

这使用连接状态,因为我不知道是否可以存储任意数量的元组状态。状态变量具有形状(batch_size,max_time_size,state_size)。

+0

您可否详细介绍一下CustomRNN代码如何返回中间状态?我正试图理解你的代码! – CentAu

+1

LSTM状态是输出(m)和隐藏状态(c)的组合。这段代码取出输出(m)并用连接状态(c + m)替换它。忽略批量大小,输出是[(c1 + m1),(c2 + m2),...]的列表,而不是[m1,m2,...]。 – jasekp

+0

因此,这会用隐藏状态(c)替换实际的输出(m),正确的('return next_state,next_state',而不是'return m,new_state')?你在哪里连接输出和隐藏状态('m + c')? – CentAu

1

我想指出你这个thread(从我的亮点):

你可以写一个返回两个状态张量作为输出的一部分LSTMCell的变体,如果你既需要Ç和每个时间步的h状态。如果您只需要h状态,那就是每个时间步的输出。

由于@jasekp在其评论中写道,输出结果真的是h部分状态。然后dynamic_rnn方法只会叠加无论在时间的h部分(见_dynamic_rnn_loopthis file字符串DOC):

def _dynamic_rnn_loop(cell, 
         inputs, 
         initial_state, 
         parallel_iterations, 
         swap_memory, 
         sequence_length=None, 
         dtype=None): 
    """Internal implementation of Dynamic RNN. 
    [...] 
    Returns: 
    Tuple `(final_outputs, final_state)`. 
    final_outputs: 
     A `Tensor` of shape `[time, batch_size, cell.output_size]`. If 
     `cell.output_size` is a (possibly nested) tuple of ints or `TensorShape` 
     objects, then this returns a (possibly nsted) tuple of Tensors matching 
     the corresponding shapes. 
+0

LSTMCell只是一个单元如果我没有弄错,则返回状态和输出。我认为'tf.nn.dynamic_rnn'的展开部分只返回最后一步。所以,我需要修改它?奇怪的是,还没有一个更高层次的解决方案。 – CentAu

相关问题