无法理解 lstm 在 tensorflow 代码示例中的使用

Having trouble understanding lstm use in tensorflow code sample

为什么要在任何训练迭代发生之前计算 pred 变量?我希望在每次迭代的 each 数据传递期间(通过 RNN() 函数)生成 pred

一定是我遗漏了什么。 pred 是不是类似于一个函数对象?我查看了 tf.matmul() 的文档,returns 是张量,而不是函数。

完整来源:https://github.com/aymericdamien/TensorFlow-Examples/blob/master/examples/3_NeuralNetworks/recurrent_network.py

代码如下:

def RNN(x, weights, biases):

    # Prepare data shape to match `rnn` function requirements
    # Current data input shape: (batch_size, n_steps, n_input)
    # Required shape: 'n_steps' tensors list of shape (batch_size, n_input)

    # Unstack to get a list of 'n_steps' tensors of shape (batch_size, n_input)
    x = tf.unstack(x, n_steps, 1)

    # Define a lstm cell with tensorflow
    lstm_cell = rnn.BasicLSTMCell(n_hidden, forget_bias=1.0)

    # Get lstm cell output
    outputs, states = rnn.static_rnn(lstm_cell, x, dtype=tf.float32)

    # Linear activation, using rnn inner loop last output
    return tf.matmul(outputs[-1], weights['out']) + biases['out']

pred = RNN(x, weights, biases)

# Define loss and optimizer
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=y))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)

# Evaluate model
correct_pred = tf.equal(tf.argmax(pred,1), tf.argmax(y,1))
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))

# Initializing the variables
init = tf.global_variables_initializer()

Tensorflow 代码有两个不同的阶段。首先,您构建一个 "dependency graph",其中包含您将使用的所有操作。请注意,在此阶段您不处理任何数据。相反,您只是定义要发生的操作。 Tensorflow 正在记录操作之间的依赖关系。

例如,为了计算 accuracy,您需要先计算 correct_pred,而要计算 correct_pred,您需要先计算 pred,等等。

所以你在显示的代码中所做的就是告诉tensorflow你想要什么操作。您已将它们保存在 "graph" 数据结构中(这是一个张量流数据结构,基本上是一个包含所有数学运算和张量的存储桶)。

稍后您将使用对 sess.run([ops], feed_dict={inputs}) 的调用对数据进行 运行 操作。

当您调用 sess.run 时,请注意您必须告诉它您想要从图中得到什么。如果你要求 accuracy:

   sess.run(accuracy, feed_dict={inputs})

Tensorflow 将尝试计算准确性。它将看到 accuracy 依赖于 correct_pred,因此它将尝试计算它,依此类推通过您定义的依赖关系图。

您犯的错误是您认为您列出的代码中的 pred 正在计算某些东西。不是。该行:

   pred = RNN(x, weights, biases)

只定义了操作及其依赖项。