我有以下 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。更详细地说,它是一个列表,其中的元素对应于时间步长,每个元素都在一个二维张量中,其中轴 0 对应于批处理索引,轴 1 对应于隐藏向量的维数。
现在,我想获取每个隐藏向量的第一个分量(将其与相应的输入向量 x 组合)。我该怎么做?
已添加
更正式地说,我需要像这样:outputs[:, :, 0]。但是,我不确定这样的事情是否会起作用,因为输出不是 3D 张量,而是 2D 张量的列表。
请您参考如下方法:
如果你真的想使用静态 RNN(顺便说一句,核心 TensorFlow 现在通过 tf.nn.static_rnn 提供静态 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]
