16

尝试在 tensorflow 中实现一个最小的玩具 RNN 示例。目标是学习从输入数据到目标数据的映射,类似于theanets 中这个精彩的简洁示例

更新:我们快到了。剩下的唯一部分是使其收敛(并且不那么复杂)。有人可以帮助将以下内容转换为运行代码或提供一个简单的示例吗?

import tensorflow as tf
from tensorflow.python.ops import rnn_cell

init_scale = 0.1
num_steps = 7
num_units = 7
input_data = [1, 2, 3, 4, 5, 6, 7]
target = [2, 3, 4, 5, 6, 7, 7]
#target = [1,1,1,1,1,1,1] #converges, but not what we want


batch_size = 1

with tf.Graph().as_default(), tf.Session() as session:
  # Placeholder for the inputs and target of the net
  # inputs = tf.placeholder(tf.int32, [batch_size, num_steps])
  input1 = tf.placeholder(tf.float32, [batch_size, 1])
  inputs = [input1 for _ in range(num_steps)]
  outputs = tf.placeholder(tf.float32, [batch_size, num_steps])

  gru = rnn_cell.GRUCell(num_units)
  initial_state = state = tf.zeros([batch_size, num_units])
  loss = tf.constant(0.0)

  # setup model: unroll
  for time_step in range(num_steps):
    if time_step > 0: tf.get_variable_scope().reuse_variables()
    step_ = inputs[time_step]
    output, state = gru(step_, state)
    loss += tf.reduce_sum(abs(output - target))  # all norms work equally well? NO!
  final_state = state

  optimizer = tf.train.AdamOptimizer(0.1)  # CONVERGEs sooo much better
  train = optimizer.minimize(loss)  # let the optimizer train

  numpy_state = initial_state.eval()
  session.run(tf.initialize_all_variables())
  for epoch in range(10):  # now
    for i in range(7): # feed fake 2D matrix of 1 byte at a time ;)
      feed_dict = {initial_state: numpy_state, input1: [[input_data[i]]]} # no
      numpy_state, current_loss,_ = session.run([final_state, loss,train], feed_dict=feed_dict)
    print(current_loss)  # hopefully going down, always stuck at 189, why!?
4

1 回答 1

6

我认为您的代码存在一些问题,但这个想法是正确的。

主要问题是您对输入和输出使用单个张量,如:
inputs = tf.placeholder(tf.int32, [batch_size, num_steps]).

在 TensorFlow 中,RNN 函数采用张量列表(因为 num_steps 在某些模型中可能会有所不同)。所以你应该像这样构造输入:
inputs = [tf.placeholder(tf.int32, [batch_size, 1]) for _ in xrange(num_steps)]

然后您需要注意您的输入是 int32s,但 RNN 单元适用于浮点向量 - 这就是 embedding_lookup 的用途。

最后,您需要调整您的提要以放入输入列表中。

我认为 ptb 教程是一个合理的地方,但如果您想要一个开箱即用 RNN 的更小示例,您可以查看一些 rnn 单元测试,例如,here。 https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/kernel_tests/rnn_test.py#L164

于 2015-12-23T04:52:50.383 回答