python - 如何在 TensorFlow 中创建并执行基本的 LSTM 网络?

标签 python tensorflow lstm

我想创建一个基本的 LSTM 网络,它接受 5 维向量序列(例如 N x 5 数组)并返回 4 维隐藏向量和单元向量(N x 4 数组)的相应序列,其中N 是时间步数。

如何使用 TensorFlow 做到这一点?

已添加

到目前为止,我已经运行了以下代码:

num_units = 4
lstm = tf.nn.rnn_cell.LSTMCell(num_units = num_units)

timesteps = 18
num_input = 5
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)

sess = tf.Session()
init = tf.global_variables_initializer()
sess.run(init)

x_val = np.random.normal(size = (12,18,5))
res = sess.run(outputs, feed_dict = {X:x_val})
sess.close()

但是,还有许多悬而未决的问题:

  1. 为什么要预设时间步数? LSTM 不应该能够接受任意长度的序列吗?
  2. 为什么我们要按时间步长分割数据(使用 unstack)?
  3. 如何解释“输出”和“状态”?

最佳答案

Why number of time steps is preset? Shouldn't LSTM be able to accept sequences of arbitrary length?

如果你想接受任意长度的序列,我建议使用dynamic_rnn。你可以引用here了解它们之间的区别。

例如:

num_units = 4
lstm = tf.nn.rnn_cell.LSTMCell(num_units = num_units)

num_input = 5
X = tf.placeholder("float", [None, None, num_input])
outputs, states = tf.nn.dynamic_rnn(lstm, X, dtype=tf.float32)

sess = tf.Session()
init = tf.global_variables_initializer()
sess.run(init)

x_val = np.random.normal(size = (12,18,5))
res = sess.run(outputs, feed_dict = {X:x_val})

x_val = np.random.normal(size = (12,16,5))
res = sess.run(outputs, feed_dict = {X:x_val})
sess.close()

dynamic_rnn 要求一批中的长度相同,但当您需要一批中的任意长度时,可以在填充批处理数据后使用 sequence_length 参数指定每个长度。

We do we split data by time-steps (using unstack)?

只是static_rnn需要用unstack来拆分数据,这取决于它们不同的输入要求。 static_rnn 的输入形状为 [timesteps,batch_size, features],它是形状为 [batch_size, features] 的 2D 张量列表。但dynamic_rnn的输入形状是[timesteps,batch_size, features][batch_size,timesteps,features],具体取决于time_major 是对还是错。

How to interpret the "outputs" and "states"?

LSTMCell中states的形状为[2,batch_size,num_units ],一个[batch_size, num_units ]代表C 另一个 [batch_size, num_units ] 代表 h。您可以看到下面的图片。

enter image description here

enter image description here

以同样的方式,您将得到GRUCell中states的形状为[batch_size, num_units]

outputs 表示每个时间步的输出,因此默认情况下(time_major=False)其形状为[batch_size, timesteps, num_units]。你可以很容易地得出结论 状态[1,batch_size,:] ==输出[batch_size,-1,:]

关于python - 如何在 TensorFlow 中创建并执行基本的 LSTM 网络?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54764500/

相关文章:

tensorflow - Keras ConvLSTM2D : ValueError when saving model

python - 具有多个输出的 LSTM 时间序列预测

python - 使用 sys.argv[1] 时为 "list index out of range"

python - 如何在 Python 中打印函数的类型注释?

python - 如何根据 Pandas 数据框的条件增加计数器?

python - 在 Tensorflow 中限制 GPU 设备

tensorflow - 如何为自定义 keras 层创建可训练的权重变量

python - 将整数从一个 def 编辑到另一个

tensorflow - 有没有办法在 Tensorflow 中处理 "Invert"神经网络?

python - 这个错误意味着什么 : `y` argument is not supported when using python generator as input