我具有以下LSTM实现:
num_units = 2
lstm = tf.nn.rnn_cell.LSTMCell(num_units = num_units)
timesteps = 100
num_input = 1
# define a computational graph
X = tf.placeholder("float", [None, timesteps, num_input])
x = tf.unstack(X, timesteps, 1)
outputs, states = tf.contrib.rnn.static_rnn(lstm, x, dtype=tf.float32)
据我了解,outputs
包含由LSTM生成的一系列隐藏向量h
。更详细地讲,它是一个列表,其中元素对应于时间步长,每个元素包含2D张量,其中轴0对应于批处理索引,轴1对应于隐藏矢量的维数。
现在,我想获取每个隐藏矢量的第一个分量(将其与相应的输入矢量x组合)。我该怎么办?
添加
更正式地说,我需要采取类似outputs[:, :, 0]
的方法。但是,由于输出不是3D张量,而是2D张量的列表,因此我不确定类似的方法是否会起作用。
答案 0 :(得分:1)
如果您真的想使用静态RNN(顺便说一句,现在可以通过tf.nn.static_rnn
在核心TensorFlow中使用静态RNN),则可以这样做:
num_units = 2
lstm = tf.nn.rnn_cell.LSTMCell(num_units = num_units)
timesteps = 100
num_input = 1
# define a computational graph
X = tf.placeholder("float", [None, timesteps, num_input])
x = tf.unstack(X, timesteps, 1)
outputs, states = tf.contrib.rnn.static_rnn(lstm, x, dtype=tf.float32)
outputs0 = [out[:, 0] for out in outputs]
如果要将这些值用作张量而不是张量列表,则可以执行以下操作:
outputs0 = tf.stack(outputs0, axis=1)
另一种选择是使用动态RNN获取张量作为输出:
num_units = 2
lstm = tf.nn.rnn_cell.LSTMCell(num_units = num_units)
timesteps = 100
num_input = 1
# define a computational graph
X = tf.placeholder("float", [None, timesteps, num_input])
outputs, states = tf.nn.dynamic_rnn(lstm, X, dtype=tf.float32)
outputs0 = outputs[:, :, 0]